1

const a = 3
const b = 4

const arr = new Array(a).fill([]);

for (let i = 0; i < a; i++) {
  for (let j = 0; j < b; j++) {
    arr[i][j] = i;
  }
}

console.log(JSON.stringify(arr))

I would expect to return

[[0,0,0,0],[1,1,1,1],[2,2,2,2]]

but it returns

[[2,2,2,2],[2,2,2,2],[2,2,2,2]]

I think this is not because of the closure things but please let me know what is the problem of this code not working as expected.

* edited -> sorry, I forgot to paste initializing arr code *

Phil
  • 157,677
  • 23
  • 242
  • 245

2 Answers2

3

Don't assign a value directly in a 2-dimension array. Initialize the first dimension first.

var arr = []
const a = 3
const b = 4

for(let i=0; i<a; i++){
  arr.push([])
  for(let j=0; j<b; j++){
      arr[i][j] = i;
  }
}

console.log(arr)

Don't initialize your array like this:

const arr = new Array(a).fill([]);

By doing this, you pass references and not values, as you could do with integers. The difference between references and values is important.

djcaesar9114
  • 1,880
  • 1
  • 21
  • 41
0

I found and post another question about Array.fill() for the other people having the same issue.

Array.fill(Array) creates copies by references not by value