a general question here, but something is not working right here, I have made a table of iterable points, using 6 arrays containing seven sub arrays each, that each individual array can be accessed with a x and y. Only problem, as depicted is when I update lets say board[0][2] It will update the entire column... even though specified,
I have compiled and sumarized the problem, and made a screenshot attached. Anyone have an idea of what might be going wrong here?
Here is my reproduced sample code
let height = 6;
let width = 6;
let board = []
let row = [];
for(let x = 0; x < width; x ){
row.push([]);
}
for(let y = 0; y < height; y ){
board.push(row)
}
board[1][5] = 1;
console.log(board)
//Output:
[
[ [], [], [], [], [], 1 ],
[ [], [], [], [], [], 1 ],
[ [], [], [], [], [], 1 ],
[ [], [], [], [], [], 1 ],
[ [], [], [], [], [], 1 ],
[ [], [], [], [], [], 1 ]
]
I am trying only to update the 5th array element of the array 1
I was expecting that the individual subArray element to be changed, and I have tried many different ways to implement this.
CodePudding user response:
maybe use Array.from
method without referenced
let height = 6;
let width = 6;
let board = []
for(let y = 0; y < height; y ){
board.push(Array.from({ length: width }, () => []))
}
board[1][5] = 1;
console.log(board)
board[0][0].push(2);
console.log(board)
CodePudding user response:
The only problem with your code is you are pushing the same array reference to the board array multiple times, as a result when you modify one of the array, all the arrays get modified.
The below code should do the trick for you !!
let height = 6;
let width = 6;
let board = []
for(let y = 0; y < height; y ){
board.push(Array(width).fill([]))
}
board[1][5] = 1;
console.log(board)