javascript中奇怪的关联数组行为

时间:2022-08-10 21:36:52

If I execute below code on chrome console then, I got answer as associative array:

如果我在chrome控制台上执行下面的代码然后,我得到了作为关联数组的答案:

var arr= [];
var i = 1;
for(var j = 1; j < 3; j++)
    arr[j]=j;console.log(arr);

Ans : [1: 1, 2: 2]

答案:[1:1,2:2]

But when i execute using node: [ , 1, 2 ]

但是当我使用node执行时:[,1,2]

Why there is so difference? As far as i know both are using v8.

为什么会有这么大的差异?据我所知,两人都在使用v8。

1 个解决方案

#1


5  

Firefox says

Firefox说

Array [ <1 empty slot>, 1, 2 ]

IE Edge says

IE Edge说

[object Array][undefined, 1, 2]

and, they're all correct

而且,他们都是正确的

Chrome is simply NOT reporting the empty index 0

Chrome只是不报告空索引0

Node is showing index 0 is empty

节点显示索引0为空

Firefox is telling you exactly what's happening

Firefox正在告诉你到底发生了什么

Try this:

尝试这个:

var arr= [];var i = 1; for(var j = 1; j < 3; j++) arr[j*3]=j+3;console.log(arr);

Firefox:

火狐:

Array [ <3 empty slots>, 4, <2 empty slots>, 5 ]

Node

节点

[ , , , 4, , , 5 ]

IE Edge

IE Edge

[object Array][undefined, undefined, undefined, 4, undefined, undefined, 5]

Chrome

[3: 4, 6: 5]

#1


5  

Firefox says

Firefox说

Array [ <1 empty slot>, 1, 2 ]

IE Edge says

IE Edge说

[object Array][undefined, 1, 2]

and, they're all correct

而且,他们都是正确的

Chrome is simply NOT reporting the empty index 0

Chrome只是不报告空索引0

Node is showing index 0 is empty

节点显示索引0为空

Firefox is telling you exactly what's happening

Firefox正在告诉你到底发生了什么

Try this:

尝试这个:

var arr= [];var i = 1; for(var j = 1; j < 3; j++) arr[j*3]=j+3;console.log(arr);

Firefox:

火狐:

Array [ <3 empty slots>, 4, <2 empty slots>, 5 ]

Node

节点

[ , , , 4, , , 5 ]

IE Edge

IE Edge

[object Array][undefined, undefined, undefined, 4, undefined, undefined, 5]

Chrome

[3: 4, 6: 5]