在 Javascript 中使用新数组创建二维数组

MrY*_*Dao 3 javascript arrays ecmascript-6

我在 Hackerrank 上尝试了一个问题,我需要在其中创建一个数组数组(基本上是二维数组)。

我的首选衬垫是const counter = new Array(4).fill([]) 但是,我意识到它会创建一个 2D 数组,但将任何函数应用于该数组都会使其应用于所有元素。

let count = new Array(4).fill([])
count[0].push("Test")
console.log(JSON.stringify(count))
Run Code Online (Sandbox Code Playgroud)

结果将是所有子数组在其中具有相同的“测试”值。

最终的解决方案是:

let count = Array.from(Array(4), () => new Array());
count[0].push("Test")
console.log(JSON.stringify(count))
Run Code Online (Sandbox Code Playgroud)

我可以问为什么它没有按预期工作吗?

Seb*_*rek 5

因为.fill()接受参数,如果它是一个对象,它会将对该对象的引用复制到新数组的每个索引中。由于实际上[]是一个对象,因此您的新数组最终会被对同一数组的引用填充。

文档

如果第一个参数是一个对象,它将复制其引用并用对该对象的引用填充数组。