Array.fill(Array)通过引用而不是按值创建副本

问题描述:

我正在尝试使用 Array.fill

let m = Array(6).fill(Array(12).fill(0));

虽然这样工作,但问题是内部数组实际上都引用了相同的 array object。

While this works, the problem is that the inner Arrays are actually all referencing the same Array object.

let m = Array(6).fill(Array(12).fill(0));
m[0][0] = 1;
console.log(m[1][0]); // Outputs 1 instead of 0

我想(和预期) m [1] [0] 0

强制 Array.fill 填充给定参数的副作用(例如: Array(12).fill(0)是我的例子),而不是通过引用复制?

How can I force Array.fill fill copy-by-values of the given argument (eg: Array(12).fill(0) is the argument in my case) instead of copying by reference ?

你不能用 Array#fill 方法。相反,迭代数组,并使用for循环添加新创建的数组。

You can't do it with Array#fill method. Instead iterate over the array and add newly created array using a for loop.

let m = Array(6);
for (var i = 0; i < m.length; i++)
  m[i] = Array(12).fill(0)

m[0][0] = 1;
console.log(m[1][0]);