0

I am facing very weird problem here with Array constructor in JavaScript. I declare an array with length 5 which further contains arrays. When I want to push an element in the first sub-array, it adds that element in all sub-arrays.

var items = new Array(5).fill([]);
items[0].push(1);
console.log(items.toString());

It gives 1,1,1,1,1, but I am expecting 1,,,,. Am I missing something here?

Suhas Bhattu
  • 539
  • 4
  • 17
  • Possible duplicate of https://stackoverflow.com/questions/66623300/modifying-value-of-matrix-filled-with-array-fill-modifies-the-whole-column – a.mola Apr 10 '21 at 09:46
  • 1
    `new Array(5).fill([]);` puts the **same** array (`[]`) in all five slots in `items`. Since it's the **same** array, any changes to its state are apparent regardless of which reference to that array you use to look. – T.J. Crowder Apr 10 '21 at 09:47

0 Answers0