Changing one cell in a multidimensional array updates the entire column
When creating a new multidimensional array in the Chrome console, follow these steps:
var array = Array(10).fill(Array(10).fill(false));
array looks like expected (check with console.table
):
But when trying to change only one cell in the array: array[5][5] = true;
something strange happens:
I bump my head against the wall because of this, but I cannot understand. Could this be a bug since Array.fill is an experimental / new feature?
source to share
This is because you actually only created two arrays. You created an inner array with 10 elements, and then an outer array that has 10 elements, each of which refers to the same inner array. When you change the element of the inner array and then look at the outer array, you will see the same change in the inner array repeated 10 times.
Create your outer array with a loop so that a new inner array is created for each element of your outer loop.
source to share