JavaScript数组长度问题

问题描述:

我有点丢失以下内容:

当我执行两个不同阵列的console.log时,一个给我实际长度但不是其他。

When I do a console.log of two different arrays, one is giving me the actual length but not the other.

第一个数组的输出,长度很好:

Output of first array, with good length:

[Object, Object, Object]
  0: Object
  1: Object
  2: Object
  length: 3
  __proto__: Array[0]

第二个的输出,长度应该是4,但实际上是0:

Output of the second one, length should be 4 but is actually 0:

[A: Object, B: Object, C: Object, D: Object]
  A: Object
  B: Object
  C: Object
  D: Object
  length: 0
  __proto__: Array[0]

为什么我的第一个阵列确实有正确的长度,而不是第二个?

Why do my first array do have a correct length, but not the second one ?

编辑
这个是产生上述输出的代码:

Edit: this is the code generating the above output:

var links = [
  {source: "A", target: "B"},
  {source: "A", target: "C"},
  {source: "A", target: "D"}
];

var nodes = [];

// Compute the distinct nodes from the links.
links.forEach(function(link) {
  link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
  link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});

console.log(links);
console.log(nodes);


第二条日志消息无法输出数组的长度因为值已经分配给它的属性而不是它的索引,因为在数组的实际索引中没有对象, length 属性是 0 。发生这种情况是因为数组不能包含非数字索引,例如A,B,C,D。

The second log message cannot output the length of the array because the values have been assigned to its properties as opposed to its indices, since there are no objects within the actual indices of the array the length property is 0. This occurs because arrays cannot contain non-numeric indices such as A,B,C,D.

所以执行时:

var arr= [];
arr["b"] = "test";

代码实际上是将字符串文字测试分配给 b arr 数组的属性,而不是索引。这是可能的,因为数组是Javascript中的对象,因此它们也可能具有属性。

The code is actually assigning the string literal test to the b property of the arr array as opposed to an index. This is possible because arrays are objects in Javascript, so they may also have properties.