Is there a function in JavaScript similar to Python\'s range()
?
I think there should be a better way than to write the following lines every time:
Still no built-in function that is equivalent to range()
, but with the most recent version - ES2015 - you can build your own implementation. Here's a limited version of it. Limited because it doesn't take into account the step parameter. Just min, max.
const range = (min = null, max = null) =>
Array.from({length:max ? max - min : min}, (v,k) => max ? k + min : k)
This is accomplished by the Array.from
method able to build an array from any object that has a length
property. So passing in a simple object with just the length
property will create an ArrayIterator that will yield length
number of objects.