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:
Is there a function in JavaScript similar to Python's range()?
As answered before: no, there's not. But you can make your own.
I believe this is an interesting approach for ES6. It works very similar to Python 2.7 range()
, but it's much more dynamic.
function range(start, stop, step = 1)
{
// This will make the function behave as range(stop)
if(arguments.length === 1)
{
return [...Array(arguments[0]).keys()]
}
// Adjusts step to go towards the stop value
if((start > stop && !(step < 0)) ||
(start < stop && !(step > 0)))
{
step *= -1
}
let returnArray = []
// Checks if i is in the interval between start and stop no matter if stop
// is lower than start or vice-versa
for(let i = start; (i-start)*(i-stop) <= 0; i += step)
{
returnArray.push(i)
}
return returnArray
}
This function can behave in three different ways (just like Python's range()):
range(stop)
range(start, stop)
range(start, stop, step)
These examples:
console.log(range(5))
console.log(range(-2, 2))
console.log(range(2, -2))
console.log(range(10, 20, 2))
Will give you the following output:
[ 0, 1, 2, 3, 4 ]
[ -2, -1, 0, 1, 2 ]
[ 2, 1, 0, -1, -2 ]
[ 10, 12, 14, 16, 18, 20 ]
Note that instead of iterating over the array with the in
operator (like python), you have to use of
. Thus the i
variable assumes the value, and not the index, of the array's element.
for(let i of range(5))
{
// do something with i...
}