Schrodinger's array: Is my array empty or full?
I am having a problem with accessing a particular array in my code. When I observe the array, it will observe correctly and will show the contents through the console. However, when I access the array, it will not let me as the array has no contents for me to access. What am I doing wrong?
Code below:
'use strict';
const DEBUG = true;
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
if (DEBUG) {
console.log('Info: Loading is complete.');
}
main();
}
}
let main = function () {
if (DEBUG) {
console.log('Info: Running main thread.');
}
let cameras = [];
let devices = navigator.mediaDevices.enumerateDevices().then(function (devices) {
for (let i = 0; i < devices.length; i++) {
let device = devices[i];
if (device.kind === 'videoinput') {
cameras.push(device);
}
}
});
console.log(cameras);
console.log('cameras.length: ' + cameras.length);
for (let i = 0; i < cameras.length; i++) {
console.log('Loop' + i);
console.log(cameras[i]);
}
console.log(cameras);
}
The output from the console:
app.js:8 Info: Loading is complete.
app.js:17 Info: Running main thread.
app.js:32 []
0: MediaDeviceInfodeviceId: "881b49d744ed5bcf922d1cb834c33eaab43f31fcb955c2a4e6938a2a3fb3a46c"
groupId: ""
kind: "videoinput"
label: "Logitech HD Webcam C615 (046d:082c)"
__proto__: MediaDeviceInfodeviceId: (...)
length: 1
__proto__: Array(0)
app.js:33 cameras.length: 0
app.js:40 []
0: MediaDeviceInfodeviceId: "881b49d744ed5bcf922d1cb834c33eaab43f31fcb955c2a4e6938a2a3fb3a46c"
groupId: ""
kind: "videoinput"
label: "Logitech HD Webcam C615 (046d:082c)"
__proto__: MediaDeviceInfodeviceId: (...)
length: 1
__proto__: Array(0)
The code is simple, it waits until the DOM is completely loaded and ready (No jQuery here). It then executes the function main(). This function creates the array cameras and then fetches all connected devices and pushes only the videoinput devices into the cameras array.
Now when I go to test the array to see if it contains anything I get two very different results.
When I observe the array using
console.log(cameras);, the console shows an array 1 device with its properties (Assuming 1 webcam is connected and working).When I access the array by any means (
console.log();orfor () {}orcameras.forEach();), it will show nothing as if the array contained no contents. Testing the array length also shows 0.
Why is this? What am I doing wrong? Any help would be greatly appreciated.
NOTE: I am using Electron 1.7.10, Node 9.2.0 and NPM 5.6.0.