When creating a new multidimensional array in Chrome's console like this:
var array = Array(10).fill(Array(10).fill(false));
the array looks as expected (inspect with console.table
):
But when trying to change only one cell in the array: array[5][5] = true;
something strange happens:
I have been banging my head against the wall for sometime because of this, but can't figure it out. Could this be a bug since Array.fill is an experimental/new feature?
Updating the 2D array We can update the elements of 2D array either by specifying the element to be replaced or by specifying the position where replacment has to be done. For updating the array we require, Elements of an array. Element or position, where it has to be inserted.
To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.
Updating Values in Python 2D Array We can update a single element in a 2D array by specifying its row and column index and assigning that array position a new value. Assigning a new value overwrites the old value, thus updating it.
In Java, elements in a 2D array can be modified in a similar fashion to modifying elements in a 1D array. Setting arr[i][j] equal to a new value will modify the element in row i column j of the array arr .
It's 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 reference the same inner array. When you change an element of the inner array and then look at the outer array, you'll see the same change in the inner array repeated 10 times.
Create your outer array with a loop instead so that a new inner array is created for every element of your outer loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With