3 ms·
> Is there any use case where you would want to deal with sparse arrays? Not really. Now explain why [,,,].map((e,i) => i) is [,,,] instead of [1,2,3] please ;
by kilburn 5y ago
> Is there any use case where you would want to deal with sparse arrays?
Not really. Now explain why [,,,].map((e,i) => i) is [,,,] instead of [1,2,3] please ;)
- 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]