我在一个类中有一个数组,当我尝试更改JavaScript中的值时,我得到了奇怪的结果。这是我控制台中的一些奇怪内容:
grid.grid
(10) [Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8)]
0: (8) [0, 0, 0, 0, 0, 0, 0, 0]
1: (8) [0, 0, 0, 0, 0, 0, 0, 0]
2: (8) [0, 0, 0, 0, 0, 0, 0, 0]
3: (8) [0, 0, 0, 0, 0, 0, 0, 0]
4: (8) [0, 0, 0, 0, 0, 0, 0, 0]
5: (8) [0, 0, 0, 0, 0, 0, 0, 0]
6: (8) [0, 0, 0, 0, 0, 0, 0, 0]
7: (8) [0, 0, 0, 0, 0, 0, 0, 0]
8: (8) [0, 0, 0, 0, 0, 0, 0, 0]
9: (8) [0, 0, 0, 0, 0, 0, 0, 0]
grid.grid[4][4] = 1;
grid.grid
(10) [Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8), Array(8)]
0: (8) [0, 0, 0, 0, 1, 0, 0, 0]
1: (8) [0, 0, 0, 0, 1, 0, 0, 0]
2: (8) [0, 0, 0, 0, 1, 0, 0, 0]
3: (8) [0, 0, 0, 0, 1, 0, 0, 0]
4: (8) [0, 0, 0, 0, 1, 0, 0, 0]
5: (8) [0, 0, 0, 0, 1, 0, 0, 0]
6: (8) [0, 0, 0, 0, 1, 0, 0, 0]
7: (8) [0, 0, 0, 0, 1, 0, 0, 0]
8: (8) [0, 0, 0, 0, 1, 0, 0, 0]
9: (8) [0, 0, 0, 0, 1, 0, 0, 0]
为什么会这样?我该如何预防?
这是我创建数组的方式:
createGrid() {
let grid = [];
let subgrid = [];
for(let i=0; i<this.cols; i++) {
subgrid.push(0);
}
for(let i=0; i<this.rows; i++) {
grid.push(subgrid);
}
return grid;
}