Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]]
like image 635
Youssef Avatar asked Dec 02 '16 12:12

Youssef


2 Answers

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.

like image 130
user3297291 Avatar answered Sep 28 '22 15:09

user3297291


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.

like image 30
Dekel Avatar answered Sep 28 '22 15:09

Dekel