Actually there's much nicer idiom to create ranges: a spreaded Array
constructor:
[...Array(n)]
creates an array of n
undefined values. To get 0..n-1
, just pick its keys
:
[...Array(n).keys()]
for arbitrary ranges, feed it to map
:
r = [...Array(10)].map((_, i) => i + 1)
console.log(r)
see here: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?
old answer:
yep, you're looking for Array.from
:
r = Array.from({length: 10}, (_, i) => i + 1);
console.log(r)
How does this work? .from
inspects its first argument (which can be any object) and picks its .length
property. Then, it iterates from 0
to length - 1
and invokes the second argument with two parameters - a value (which is undefined unless the first argument contains a corresponding numeric property) and an index, which takes values from 0...length-1
. In this example, we have a function that just returns an index + 1, thus giving us 1..length
.
Here's a useful wrapper for the above:
let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);
console.log(range(1, 10))
For ES5, the idiom is Array.apply(null, {length:N})
:
r = Array.apply(null, {length: 10}).map(function(_, i) {
return i + 1
})