Skip to content Skip to sidebar Skip to footer

Weird Behaviour In Array.fill

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); /

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Weird Behaviour In Array.fill"