Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding javascript Array() function [duplicate]

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.

like image 898
graciano Avatar asked Nov 07 '22 15:11

graciano


1 Answers

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 undefineds { 0: undefined, 1: undefined, 2: undefined, length: 3 }. And .map only iterates over existing keys.

like image 159
Jonas Wilms Avatar answered Nov 15 '22 06:11

Jonas Wilms