Today I was porting my Python code into JavaScript and found this behavior.
Code:
var a = new Array(2).fill(new Array(3).fill([0, 0]));
for (i=0; i<2; i++) {
for (j=0; j<3; j++) {
a[i][j] = [i, j];
//console.table(a); //for debugging
}
}
What I think I should get for a
(as a 2-dim array):
--------------------------
[0, 0] | [0, 1] | [0, 2] |
--------------------------
[1, 0] | [1, 1] | [1, 2] |
--------------------------
What JavaScript gave me:
--------------------------
[1, 0] | [1, 1] | [1, 2] |
--------------------------
[1, 0] | [1, 1] | [1, 2] |
--------------------------
It looks like there's some other type of logic used in JavaScript than what I think it should be. I'm simply assigning [i, j]
to the [i][j]
-th entry, but the result is not what I have in mind.
- Have I made a mistake in the code?
- Why is the for-loop logic doesn't work in JavaScript?
- What should I do to get the desired result then?