If I write this code: Array(3).map( () => ({ a:1 }) )
I get Array(3) [ <3 empty slots> ]
instead of an array of 3 objects. Why is that?
As far as I know, Array(3)
will produce an array of undefined
elements with length 3. And for instance, [1, 2, 3].map( () => ({ a:1 }) )
produces the expected output. This is true also using any other array with length 3. I'm intrigued.
Array(3)
creates an empty array of length 3. Or as an object it would be { length: 3 }
. With, e.g. Array(Array(3))
you would create an array with undefined
s { 0: undefined, 1: undefined, 2: undefined, length: 3 }
. And .map
only iterates over existing keys.
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