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 *

2
  • Where is arr defined? Commented Jun 11, 2020 at 0:13
  • @Phil Oh I missed it. Would you check it again? Commented Jun 11, 2020 at 0:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I do edit my code. can you check it again? Your code work properly but I cannot understand why my code is still returns the unexpected result..
I explained the mistake you made.
Checked! really appreciate it :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.