(new array (x)).

I found strange behavior (tested in Chrome)

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

and this is normal - well, as in the documentation But

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

It does not use a callback (no action, the debugger inside does not work, etc.). Why??

The syntax new Array(arrayLength) should create an array with the given length. And so it is. But what about .map ?

+7
javascript arrays
source share
1 answer

From MDN :

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

When you declare an array using new Array() , all elements are undefined, but they were not assigned undefined as a value. Therefore, they are skipped when calling map() .

You can use join() and split() to explicitly assign undefined for each element, and you will get the expected result:

 (new Array(20).join(undefined).split(undefined)).map(function() { console.log(arguments); }) 
+8
source share

All Articles