I want to create a 10x10
array filled with 0
values, which I though I could do like this:
var myArray = new Array(10).fill(new Array(10).fill(0));
This is working fine, but there's a problem when I try to change one of the values in the array, for example:
myArray[2][3] = 6;
Instead of changing just the one value, the output is this:
0 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
1 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
2 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
3 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
4 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
5 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
6 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
7 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
8 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
9 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
As you can see, all values in the column with index 3
have been changed. Why is this, and how do I create a new, zero-filled array without this happening?
var myArray = new Array(10).fill(new Array(10).fill(0));
console.log("--------Before--------");
console.log(myArray);
myArray[2][3] = 6;
console.log("--------After---------");
console.log(myArray);