Shawn's point was not to find a solution that does not use a for loop. Shawn's point was to demonstrate why the code that one would expect to work does not:
Array(100).map((_,i)=>i)
It looks simple, but does not work in Javascript, due to this array-is-an-object thingy. That's the point.
I'm not sure if I would go with Shawn's spread operator solution or if I'd just go back to a simple for loop. But I'm pretty sure that Array.apply(null, ...) and Elarcis' Array.from(...) are not solutions that are easy to understand (no offence), they both seem to be workarounds.
Why not just
[...Array(5).keys()];
?For history’s sake, it’s equivalent to:
Shawn's point was not to find a solution that does not use a for loop. Shawn's point was to demonstrate why the code that one would expect to work does not:
It looks simple, but does not work in Javascript, due to this array-is-an-object thingy. That's the point.
I'm not sure if I would go with Shawn's spread operator solution or if I'd just go back to a simple for loop. But I'm pretty sure that Array.apply(null, ...) and Elarcis' Array.from(...) are not solutions that are easy to understand (no offence), they both seem to be workarounds.
To be honest, with regard to the article, I find it quite weird that
Array(5).keys()
does work. 🤔It doesn’t!
The
...
fires first and producesArray.apply(null, Array(5)).keys()
Then that is expanded to
Array(undefined, undefined, undefined, undefined, undefined).keys()
.Since the Array was created by a list of items, keys returns
[0,1,2,3,4]
JavaScript needs a range operator or a Texas range notation. Just so I don’t need to hide the splat under a function to increase readability.
Makes sense, thanks. I struggle with splat operator execution order from time to time.
In trying to rewrite the above code I ended up having to experiment a bit to figure out what was happening when... it’s certainly far from obvious.
This also works!