I'm trying to update every element of a 2d array only once. But unexpectedly array item gets update multiple times.
For example:
const s = "ab";
const m = [...Array(s.length).fill([...Array(s.length).fill("")])]
for(let row = 0; row < s.length; row++) {
for (let col = 0; col < s.length; col++) {
console.log(row, col)
m[row][col] += `<${row}${col}>`
}
}
console.log(m)
it should return
m=[ [ '<00>', '<01>' ], [ '<10>', '<11>' ] ]
but it returns
m=[ [ '<00><10>', '<01><11>' ], [ '<00><10>', '<01><11>' ] ]instead.
Can anyone explain it, please?
Update:
Here I'm looping through each item once, so there should be no chance of updating the item twice ( two value should not concat here )