Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate new array in javascript

Trying to allocate new array with values.

Case 1 :

var x = new Array(3).map(()=>1);

Now x is [undefined * 3]

Case2 :

var x = [...new Array(3)].map(()=>1);

And now x is [1,1,1]

Can someone help here?

Why using this spread operator makes such a difference?

And why Case 1 doesn't work ?

like image 932
WreckingBall Avatar asked May 11 '16 00:05

WreckingBall


2 Answers

tl;dr: The first array has holes, the second one doesn't. .map skips holes.


By using a spread element, the array is treated as an iterable, i.e. you get an iterator to iterate over the array. The iterator basically works like a for loop, it will iterate the array from index 0 to index array.length - 1 (see the spec for details), and add the value at each index to the new array. Since your array doesn't contain any values, array[i] will return undefined for every index.

That means, [...new Array(3)] results in an array that literally contains three undefined values, as opposed to just a "spare" array of length 3.

See the difference in Chrome:

enter image description here

We call "sparse arrays" also "arrays with holes".

Here is the crux: Many array methods, including .map, skip holes! They are not treating the hole as the value undefined, the completely ignore it.

You can easily verify that by putting a console.log in the .map callback:

Array(3).map(() => console.log('call me'));
// no output

And that's the reason your first example doesn't work. You have a sparse array with only holes, which .map ignores. Creating a new array with the spread element creates an array without holes, hence .map works.

like image 116
Felix Kling Avatar answered Sep 20 '22 21:09

Felix Kling


Array

arrayLength

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number.

new Array(3) does not actually create iterable values at created array having .length property set to 3.

See also Undefined values with new Array() in JavaScript .

You can use Array.from() at first example to return expected results

var x = Array.from(Array(3)).map(()=>1);

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

var x = [...new Array(10)].map(()=>1);

creates an array having values undefined and .length set to 10 from Array(10), which is iterable at .map()

like image 33
guest271314 Avatar answered Sep 17 '22 21:09

guest271314