If you're looking for a more elegant way to generate ranges in JavaScript, consider using the spreaded Array
constructor:
[...Array(n)]
This will create an array filled with n
undefined values. To get the range 0..n-1
, simply access its keys
:
[...Array(n).keys()]
For more complex ranges, you can utilize the map
function:
r = [...Array(10)].map((_, i) => i + 1)
console.log(r)
For further information on this topic, check out: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?
Prior to this method, another option was using Array.from
:
r = Array.from({length: 10}, (_, i) => i + 1);
console.log(r)
The `from` method inspects the length property of its first argument (which can be any object), and then iterates from 0 to length - 1, calling the second argument with a value parameter that is undefined unless the object has corresponding numeric properties, along with an index parameter from 0 to length - 1. In this case, we use a function that returns the index + 1, resulting in a sequence from 1 to length.
To simplify the process, here's a handy wrapper function:
let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);
console.log(range(1, 10))
Alternatively, for ES5 compatibility, you can use Array.apply(null, {length:N})
:
r = Array.apply(null, {length: 10}).map(function(_, i) {
return i + 1
})