I'm having trouble with an array that doesn't hold the final values it should, but I'm unsure what is causing this issue. As I log the values I can see that I'm storing what I intend for every tempArr[row][col], but when I log tempArr after the for loop is complete my values are not what they should be. With the code provided below, does anybody know where I'm going wrong?
let tempArr = new Array(3)
.fill(new Array(3)
.fill({
color: 'white'
}));
for(let row = 0; row < 3; row ){
for(let col = 0; col < 3; col ){
console.log(board[row][col]);
tempArr[row][col] = board[row][col]
console.log(tempArr[row][col]);
console.log("----");
if(row === 2 && col === 2) {
console.log(tempArr);
done = true;
break;
}
}
if (done) break;
}
console.log(tempArr);
CodePudding user response:
All your arrays have the same reference. Array.fill will fill the array with the same reference.
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
From the docs:
If the first parameter is an object, each slot in the array will reference that object.
For understanding see the difference between the two outputs below.
In the first one: I am returning a new array for every row using map. In the second one (which is same as your code), all your rows point to the same array instance.
let tempArr = new Array(3)
.fill(0).map((x) => new Array(3)
.fill(0));
let x = 0;
for(let row = 0; row < 3; row ){
for(let col = 0; col < 3; col ){
tempArr[row][col] = x ;
}
}
console.log(tempArr);
let tempArr2 = new Array(3)
.fill(new Array(3)
.fill(0));
let y = 0;
for(let row = 0; row < 3; row ){
for(let col = 0; col < 3; col ){
tempArr2[row][col] = y ;
}
}
console.log(tempArr2);
Notice how the log here says /**ref:2**/
. In chrome console, you will see the values, which will make it more clear. The output would be :