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

): enter image description here

But when trying to change only one cell in the array: array[5][5] = true;

something strange happens: enter image description here

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?

+2


source to share


1 answer


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.

+2


source







All Articles