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)
我可以问为什么它没有按预期工作吗?
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |