I am doing some Javascript Matrix exercises and came across the problem of my Matrix not updating as expected when it's created using the Javascript Array constructor.
I created a matrix called theatre:
const theatre = new Array(5).fill(new Array(10).fill(0));
which prints as expected:
console.log(theatre)
[ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
however, when I attempt to change the values of each element in the first two rows to 1, every value in the matrix is changed.
for(let i = 0; i < 2; i++){
for(let j = 0; j < 10; j++){
theatre[i][j] = 1;
}
}
console.log(theatre)
[ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ]
To test further, I updated theatre to be equal to a matrix instead of using the array constructor and ran the for loop again which returned the expected output.
const theatre = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
for(let i = 0; i < 2; i++){
for(let j = 0; j < 10; j++){
theatre[i][j] = 1;
}
}
console.log(theatre)
[ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
Why doesn't this logic work as expected on the matrix created with the Array constructor? Am I misunderstanding how the array constructor works with fill?