Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arr.map differs from Array.from for an array with no values

Tags:

javascript

I always assumed Array.from behaves the same as Array.map for array. But it seems that for array with no initial values, they are totally different.

arr = new Array(5); 
range = Array.from(arr, (v,idx) => idx); // [0,1,2,3,4]
new_arr = arr.map((v, idx) => {return idx;}); // [undefined, undefined,undefined, undefined,undefined]

So Array.from was still able to get the indices, while arr.map here just skips through all the values, actually it never calls the callback function.

How does JavaScript handles an array with no initial values?

like image 398
smilence Avatar asked Mar 08 '20 03:03

smilence


1 Answers

new Array(5) creates a sparse array, that is an array with a length of 5 but actually no entries - the elements 0-4 are not just undefined, they actually don't exist. (0 in arr === false)

You are writing above that the result of map is [undefined, undefined, ...] but actually it is another sparse array with no elements. In Chrome Devtools, you'd see this as [empty × 5] instead.

Array.from specifically has the purpose to create a regular array out of array-like things. It basically checks for a length property and creates a new array out of whatever is returned from [0], [1], ..., [length - 1]. Therefore, it turns the sparse array into a dense array with 5x undefined in it, and your callback is called for elements 0-4.

Array.prototype.map however just iterates over the (existing!) elements in the array and returns a new array with the mapped values. Note that the sparse array has no elements, hence your callback is never called, and the returned array looks the same as before.

like image 103
CherryDT Avatar answered Sep 26 '22 05:09

CherryDT