Weird behaviour in Array.fill [duplicate]

When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:

var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr); 
//=> prints [[5], [5]]

Answers:

Answer

fill is essentially doing this:

var content = [];
for (var i = 0; i < 2; i += 1) {
  arr[i] = content;
}

So, your array will have a reference to the array you've passed to fill in each property.

Answer

It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.

It's exactly the same as:

var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);

You can see that the values inside the arr are affected by the change to the a array.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.