I am currently going over the WebRTC tutorial on their docs when I noticed that they use forEach after their usage of map(). In order to use forEach and expect a value instead of undefined array, map() would have needed to return an array, which I don't see how it can, because it doesn't return anything.
function updateCameraList(cameras) {
const listElement = document.querySelector('select#availableCameras');
listElement.innerHTML = '';
cameras.map(camera => {
const cameraOption = document.createElement('option');
cameraOption.label = camera.label;
cameraOption.value = camera.deviceId;
}).forEach(cameraOption => listElement.add(cameraOption));
}
CodePudding user response:
The code will not work since the map returns nothing.
options.label is not supported well by all browsers
Here is a better method
function updateCameraList(cameras) {
document.getElementById('availableCameras').innerHTML = cameras
.map(({label, deviceId}) => `<option value="${deviceId}">${label}</option>`)
.join("");
}
CodePudding user response:
The code is clearly missing a line. The code should be pushing undefined into an array and that would be appended to the select.
function updateCameraList(cameras) {
const listElement = document.querySelector('select#availableCameras');
listElement.innerHTML = '';
cameras.map(camera => {
const cameraOption = document.createElement('option');
cameraOption.label = camera.label;
cameraOption.value = camera.deviceId;
return cameraOption;
}).forEach(cameraOption => listElement.add(cameraOption));
}
Now why would we need to loop twice, it is a bit of a waste of time. So I would just loop once.
function updateCameraList(cameras) {
const listElement = document.querySelector('select#availableCameras');
listElement.innerHTML = '';
cameras.forEach(camera => {
const cameraOption = document.createElement('option');
cameraOption.label = camera.label;
cameraOption.value = camera.deviceId;
listElement.add(cameraOption));
});
}