Array.fill() 然后更改二维数组中的值会为 JS 中的列提供相同的输出
Array.fill() then changeing the value in a 2D array gives the same output for a column in JS
所以我用 0 填充了这个二维数组
然后更改此二维数组第一行中的第一个值
但是它改变了每一行的第一个值,有人知道为什么会这样吗?
let arr = Array<number[]>(5).fill(Array<number>(5).fill(0));
arr[0][0] = 10;
console.log(arr);
输出
[
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ]
]
预期输出
[
[ 10, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ]
]```
Array.prototype.fill()
sets each element in the array to the specified value. To generate an array filled with possibly different values you can use Array.from()
:
let arr = Array.from({ length: 5 }, () => Array<number>(5).fill(0));
所以我用 0 填充了这个二维数组 然后更改此二维数组第一行中的第一个值 但是它改变了每一行的第一个值,有人知道为什么会这样吗?
let arr = Array<number[]>(5).fill(Array<number>(5).fill(0));
arr[0][0] = 10;
console.log(arr);
输出
[
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ],
[ 10, 0, 0, 0, 0 ]
]
预期输出
[
[ 10, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ]
]```
Array.prototype.fill()
sets each element in the array to the specified value. To generate an array filled with possibly different values you can use Array.from()
:
let arr = Array.from({ length: 5 }, () => Array<number>(5).fill(0));