I want to change only the first column in the firs row but it doesn’t work.
wanted output is [[1,0],[0,0]], but what I get is[[1,0],[1,0]]
I want to know why this happens and what is the solution if I want to make a change in a different index ?
let matrix = [];
let row = [0, 0];
for (i = 0; i < 2; i++) {
matrix.push(row);
}
matrix[0][0] = 1;
console.log(matrix);
>Solution :
The problem is, that you are pushing the same object (row) into the matrix twice.
Make a copy of row for example with the spread operator, or Array.slice():
let matrix = [];
let row = [0, 0];
for (i = 0; i < 2; i++) {
matrix.push([...row]);
}
matrix[0][0] = 1;
console.log(matrix);