Sometimes, we want to create array with function similar to Python range() with JavaScript.
In this article, we’ll look at how to create array with function similar to Python range() with JavaScript.
How to create array with function similar to Python range() with JavaScript?
To create array with function similar to Python range() with JavaScript, we can use the Array
constructor and the spread operator.
For instance, we write
const range = (n) => [...Array(n).keys()];
to create an array with length n
with Array(n)
.
Then we call keys
to return an array of indexes of the array.
And then we spread the indexes of the array into a new array.
Conclusion
To create array with function similar to Python range() with JavaScript, we can use the Array
constructor and the spread operator.