I would like to know why these two arrays' results differ when I assign new values to them:
let arrLiteral = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
];
let arrFill = Array(3).fill(Array(3).fill(0));
console.log("*** BEFORE UPDATE ***");
console.log("Array Literal", arrLiteral);
console.log("Array Fill", arrFill);
let words = ["abc", "def", "g"];
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < words[i].length; j++) {
arrLiteral[i][j] = words[i][j];
arrFill[i][j] = words[i][j];
}
}
console.log("*** AFTER UPDATE ***");
console.log("Array Literal", arrLiteral);
console.log("Array Fill", arrFill);
Logs look like this:
*** BEFORE UPDATE ***
Array Literal [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
Array Fill [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
*** AFTER UPDATE ***
Array Literal [ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g', 0, 0 ] ]
Array Fill [ [ 'g', 'e', 'f' ], [ 'g', 'e', 'f' ], [ 'g', 'e', 'f' ] ]
Thanks in advance for any hints.