提问者:小点点

NodeJS数组。长度异常行为


今天我注意到了一些不寻常的事情,不知道有人有什么解释的想法。我正在测试NodeJS中填充在for循环中的数组的长度。类似于下面的代码片段。

// 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)

在对for循环进行迭代之后,console.log的输出为:

[ 'Qubino Energy Monitor': '0159-0007-0052' ] 0

数组中的元素是我所期望的,device.label和设备的id的键值对。不需要0的长度,因为数组中有一个条目。

我将循环改为追加值:

// 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)

在遍历for循环之后,console.log的输出现在是:

[ '0159-0007-0052' ] 1

长度的输出现在已经增加到1,这是预期的,并且我已经从数组条目中删除了键,所以一切都是正确的。

如果我想获得数组中的键,值对象以及它增加的长度,我必须先创建对象,然后将它推入数组。

// 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)

console.log现在返回:

[ { 'Qubino Energy Monitor': '0159-0007-0052' } ] 1

如预期的那样,索引为0的对象,使数组长度为1。

为什么在第一种情况下,数组的长度为0


共3个答案

匿名用户

标签道具是否包含数字?一个数组,用来处理内部转换为字符串的数字(就像普通JS-object中的键一样)。比较:

let array = []
arr[3] = 1 // arr.length = 4
let array = []
arr['abc'] = 2 // arr.length = 0

匿名用户

当您将数组视为字典时

ids[devices[i].label] = id

查看简化代码段:

null

const devices = [{deviceManufacturerCode:'100-01', label: 'foo'}]

// 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
  ids[devices[i].label] = id
}
console.log(ids,ids.length)

匿名用户

那是很平常的行为。因为在第一个示例中,您不是在数组中添加项,而是在“ids”对象中添加属性。例如,如果您执行如下操作,您将正确地索引数组:

var arr = []
arr[1] = "foo"
console.log(arr.length)
// output: 2

另请参阅:为什么数组中的字符串索引不增加“长度”?