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
?
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); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With