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
There is another way in ES6, using Array.from which takes 2 arguments, the first is an arrayLike (in this case an object with length
property), and the second is a mapping function (in this case we map the item to its index)
Array.from({length:10}, (v,i) => i)
this is shorter and can be used for other sequences like generating even numbers
Array.from({length:10}, (v,i) => i*2)
Also this has better performance than most other ways because it only loops once through the array. Check the snippit for some comparisons
// open the dev console to see results
count = 100000
console.time("from object")
for (let i = 0; i i )
}
console.timeEnd("from object")
console.time("from keys")
for (let i =0; i