Why Does .map Treat Array(x) Differently From [...array(x)]?
The question is, what is the difference between Array(5) and [...Array(5)] See below variable c and d is the same yet .map treats it differently. let a = [...Array(5)].map((k,i)=&g
Solution 1:
Because when you directly call Array(5)
, it creates an empty array, not an array with 5 undefined
. This is why nothing happens when you call map because there is nothing for it to iterate over, so it immediately returns.
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array
Post a Comment for "Why Does .map Treat Array(x) Differently From [...array(x)]?"