This is probably a duplicate question but I didn't know how to search for it.
Can someone explain the bevior from the code snippet to me?
I am trying to iterate over a 2-dimensional array, setting each value to the index of the containing row. Yet all values are somehow set to the last row's index.
const string1 = "abc";
const string2 = "abcd";
const matrix = new Array(string1.length).fill(new Array(string2.length).fill(0));
for (let i = 0; i < string1.length; i++) {
for (let j = 0; j < string2.length; j++) {
console.log(i);
matrix[i][j] = i;
}
}
console.log(matrix);
Output:
0
0
0
0
1
1
1
1
2
2
2
2
[ [ 2, 2, 2, 2 ], [ 2, 2, 2, 2 ], [ 2, 2, 2, 2 ] ]
Expected output:
0
0
0
0
1
1
1
1
2
2
2
2
[ [ 0, 0, 0, 0 ], [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ] ]