Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不同初始化方法下的Javascript数组差异_Javascript_Arrays_Node.js - Fatal编程技术网

不同初始化方法下的Javascript数组差异

不同初始化方法下的Javascript数组差异,javascript,arrays,node.js,Javascript,Arrays,Node.js,有人能解释一下为什么Javascript控制台(节点7.2.0)中会发生以下情况: 示例I中的数组与示例II和III中的数组具有不同的行为 示例一 > var x = new Array(3).fill(new Array(2).fill(0)) > x [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ] > x[0][0] = 1; > x [ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ] ] 示例二 > var y = [...new

有人能解释一下为什么Javascript控制台(节点7.2.0)中会发生以下情况:

示例I中的数组与示例II和III中的数组具有不同的行为

示例一

> var x = new Array(3).fill(new Array(2).fill(0))
> x
[ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> x[0][0] = 1;
> x
[ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ] ]
示例二

> var y = [...new Array(3)].map(()=>{return [...new Array(2)].map(()=>0)})
> y
> [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> y[0][0] = 1
> [ [ 1, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> var y = []
> y.push([ 0, 0 ])
> y.push([ 0, 0 ])
> y.push([ 0, 0 ])
> y
> [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> y[0][0] = 1
> [ [ 1, 0 ], [ 0, 0 ], [ 0, 0 ] ]
示例三

> var y = [...new Array(3)].map(()=>{return [...new Array(2)].map(()=>0)})
> y
> [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> y[0][0] = 1
> [ [ 1, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> var y = []
> y.push([ 0, 0 ])
> y.push([ 0, 0 ])
> y.push([ 0, 0 ])
> y
> [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> y[0][0] = 1
> [ [ 1, 0 ], [ 0, 0 ], [ 0, 0 ] ]
似乎初始化数组的不同方法会导致数组的不同行为。我很困惑,提前向您表示感谢。

返回修改后的数组,因此您正在用对同一数组的多个引用填充一个数组。这就是为什么当您在一个位置修改它时,它会自动显示在其他位置

第一个示例相当于执行以下操作:

var arr = [ 0, 0 ];
var x = [ arr, arr, arr ];

差异的原因是在JS中,对象(包括数组)不是复制的,而是链接的。在示例I中,使用单个数组填充数组

> var x = new Array(3).fill(new Array(2).fill(0))
// You have filled x with three links to the same array
> x
[ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> x[0][0] = 1;
// You have now modified the actual array, this change is reflected in all the links to it.
> x
[ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ] ]
您所做的与所做的相同:

var a = [ 0, 0 ]
var x = [ a, a, a ]



顺便说一句,使用
newarray()
通常是一种不好的做法。数组文字语法没有任何好处。另外,使用
new Array(n)
会在数组中产生“空插槽”,这很奇怪,如果不填充所有插槽,可能会导致程序出现问题。

我不这么认为,我专门使用new操作符为fill函数创建一个新数组,以避免使用相同的引用。
new Array()
一次创建一个数组
array.fill()
不复制,它只是将数组元素分配给传递给它的任何对象(在本例中是单个数组)。