I created a 2D matrix in two different ways in JavaScript.
Both approaches initialize to an identical state (double nested arrays with each grid set to 0
).
However the first approach (dp1
) later becomes an issue when referencing the indices for some reason. I'm assuming it has something to do with nesting the new
keyword.
const dp1 = new Array(6).fill(new Array(4).fill(0));
const dp2 = new Array(6);
for (let i = 0; i < 6; i ) {
dp2[i] = new Array(4).fill(0);
}
for (let i = 5; i >= 0; i--) {
for (let j = 3; j >= 0; j--) {
dp1[i][j] = `${i}, ${j}`;
dp2[i][j] = `${i}, ${j}`;
}
}
console.log(dp1);
console.log(dp2);
dp2
results in this (which is how it should be):
(6) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)]
0: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
1: (4) ['1, 0', '1, 1', '1, 2', '1, 3']
2: (4) ['2, 0', '2, 1', '2, 2', '2, 3']
3: (4) ['3, 0', '3, 1', '3, 2', '3, 3']
4: (4) ['4, 0', '4, 1', '4, 2', '4, 3']
5: (4) ['5, 0', '5, 1', '5, 2', '5, 3']
But, dp1
results in this:
(6) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)]
0: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
1: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
2: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
3: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
4: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
5: (4) ['0, 0', '0, 1', '0, 2', '0, 3']
CodePudding user response:
dp1
is filled with the same array instance because there's only one constructor call. dp2
is filled with distinct arrays.
So any time you change something in dp1
, it's changed in all lines.
The last iteration sets the first row to ['0, 0', '0, 1', '0, 2', '0, 3']
so all rows are set to ['0, 0', '0, 1', '0, 2', '0, 3']
in dp1
.