Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(new Array(x)).map stranges [duplicate]

I found strange behavior ( tested at Chrome )

[1,2].map(function() { console.log(arguments); })
// [1, 0, Array[2]]
// [2, 1, Array[2]]
// [undefined, undefined]

and that's ok -- ok as in documentation But

(new Array(20)).map(function() { console.log(arguments); })
//[undefined × 20]

It doesn't use callback ( no actions, debugger inside doesn't work etc. ). Why??

Syntax new Array(arrayLength) should create array with given length. And it does. But what with .map?

like image 962
Vasiliy Vanchuk Avatar asked Jan 21 '16 19:01

Vasiliy Vanchuk


Video Answer


1 Answers

From MDN:

callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

When you declare an array using new Array(), all of the elements are undefined, but they have not been assigned undefined as a value. Therefore, they are skipped in the call to map().

You can use join() and split() to explicitly assign undefined to each element, and you'll then get the expected output:

(new Array(20).join(undefined).split(undefined)).map(function() { console.log(arguments); })
like image 170
Rick Hitchcock Avatar answered Oct 07 '22 01:10

Rick Hitchcock