这个问题在这里已经有了答案:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 个回答)
去年关闭。
我在 Hackerrank 上尝试了一个问题,我需要在其中创建一个数组数组(基本上是二维数组)。
我的首选类轮是 const counter = new Array(4).fill([])
但是,我意识到它会创建一个 2D 数组,但是将任何函数应用于数组都会使其应用于所有元素。
let count = new Array(4).fill([])
count[0].push("Test")
console.log(JSON.stringify(count))
结果将是所有子数组在其中具有相同的“测试”值。
最终的解决方案是:
let count = Array.from(Array(4), () => new Array());
count[0].push("Test")
console.log(JSON.stringify(count))
我可以问为什么它没有按预期工作吗?
最佳答案
因为 .fill()
接受参数,如果它是一个对象,它会将对该对象的引用复制到新数组的每个索引中。因为事实上[]
是一个对象,你的新数组最终会被对同一个数组的引用填充。
来自 docs :
If the first parameter is an object, it will copy its reference and fill the array with references to that object.
关于javascript - 在 Javascript 中使用新数组创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60395789/