I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.
var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
To me it feels like there should be a way of doing this without the loop.
Best Answer
In ES6 using Array from() and keys() methods.
Shorter version using spread operator.
Start from 1 by passing map function to Array from(), with an object with a
length
property: