new Array(3)
returns an array of length 3 containing 3 undefined
s which is equivalent to [undefined, undefined, undefined]
;
However,
[undefined, undefined, undefined].map((val, i) => i)
produces the expected result of [0, 1, 2]
. But new Array(3).map((val, i) => i)
produces [undefined, undefined, undefined]
, as if the map function had not effect whatsoever.
Could anyone explain why?
EDIT
Looks like there is a flaw in my understanding of new Array()
. It does NOT create a new array. It creates an object with key length
equal to the argument passed in. Thanks for the answers and comments.
Btw if you do need an array like [undefined, undefined, undefined]
to iterate/map over, or for anything then [...new Array(m)]
should do the trick.