Categories
JavaScript Answers

How to create array with function similar to Python range() with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *