3 ms·
(assuming you're really asking) It's because JS has a notion of array elements being "empty", and the map operation skips empty elements. Basically "empty" mean
by fenomas 5y ago
(assuming you're really asking) It's because JS has a notion of array elements being "empty", and the map operation skips empty elements. Basically "empty" means the element has never had a value assigned to it, but its index is less than the array's length property.
Array(4) // [empty × 4]
a=[]; a.length=4; a // [empty × 4]
Array(4).map(n => n) // [empty × 4]
[,,1,,].map(n => n) // [empty × 2, 1, empty]
My go-to way of avoiding this annoyance is "Array.from(Array(N))":
Array.from(Array(4)).map((n,i) => i) // [0, 1, 2, 3]
Alternately there's a recent "fill" method, that assigns all elements (including empty ones) to a given value:
Array(4).fill(1) // [1, 1, 1, 1]