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 runt
Object.keys(Array.apply(0, Array(3))).map(Number)
Returns [0, 1, 2]
. Very similar to Igor Shubin's excellent answer, but with slightly less trickery (and one character longer).
Array(3) // [undefined × 3]
Generate an array of length n=3. Unfortunately this array is almost useless to us, so we have to…Array.apply(0,Array(3)) // [undefined, undefined, undefined]
make the array iterable. Note: null's more common as apply's first arg but 0's shorter.Object.keys(Array.apply(0,Array(3))) // ['0', '1', '2']
then get the keys of the array (works because Arrays are the typeof array is an object with indexes for keys.Object.keys(Array.apply(0,Array(3))).map(Number) // [0, 1, 2]
and map over the keys, converting strings to numbers.