I noticed something unusual today and wondered of anyone had any ideas of explanantion. I am testing the length of an array in NodeJS which is populated within a for loop. Something like the code snippet below.
// Set up an array to hold the IDS
var ids = []
// Iterate through each of the devices 
for (let i = 0; i < devices.length; i++) {
  let id = devices[i].deviceManufacturerCode
  if (id == qubino_id){
    ids[devices[i].label] = id
   }
}
console.log(ids,ids.length)
The output from the console.log after the for loop is iterated through is:
[ 'Qubino Energy Monitor': '0159-0007-0052' ] 0
The elements in the array are what I expected, a key value pair of the device.label and the id of the device. The length of 0 is not expected though as there is an entry in the array.
I changed the loop to append values instead:
// Set up an array to hold the IDS
var ids = []
// Iterate through each of the devices 
for (let i = 0; i < devices.length; i++) {
  let id = devices[i].deviceManufacturerCode
  if (id == qubino_id){
    ids.push(id) // CHANGE HERE 
   }
}
console.log(ids,ids.length)
The output from the console.log after the for loop is iterated through is now:
[ '0159-0007-0052' ] 1
The output of length has now increased to 1 which is expected and I have dropped the key from the array entry so everything is correct.
If I want to get the key, value object in the array and the length it increase I have to create the object first then push it to the array.
// Set up an array to hold the IDS
var ids = []
// Iterate through each of the devices 
for (let i = 0; i < devices.length; i++) {
  let id = devices[i].deviceManufacturerCode
  if (id == qubino_id){
    let name = devices[i].label
    let obj = {}
    obj[name] =  id  
    ids.push(obj)
   }
}
console.log(ids,ids.length)
The console.log now returns:
[ { 'Qubino Energy Monitor': '0159-0007-0052' } ] 1
As expected an object at index 0, making the array length of 1.
Why in the first case am I getting a length of 0 for the array?
 
     
     
    