【发布时间】:2014-09-17 11:58:24
【问题描述】:
我对以下内容有点迷茫:
当我对两个不同的数组进行 console.log 时,一个是给我实际长度,而不是另一个。
第一个数组的输出,长度合适:
[Object, Object, Object]
0: Object
1: Object
2: Object
length: 3
__proto__: Array[0]
第二个的输出,长度应该是4但实际上是0:
[A: Object, B: Object, C: Object, D: Object]
A: Object
B: Object
C: Object
D: Object
length: 0
__proto__: Array[0]
为什么我的第一个数组确实有正确的长度,而第二个却不是?
编辑: 这是生成上述输出的代码:
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 of JavaScript Object Array
-
第二种语法应该是什么鬼?
[...]用于没有键的数组;{...}用于对象,可以。 -
@MarkReed 数组可以有属性(它们不算作索引元素);请参阅有关凯文回答的讨论。
标签: javascript arrays