Home > Web Front-end > JS Tutorial > What's the Most Efficient Way to Create a JavaScript Array from 1 to N?

What's the Most Efficient Way to Create a JavaScript Array from 1 to N?

Susan Sarandon
Release: 2024-12-16 14:01:10
Original
667 people have browsed it

What's the Most Efficient Way to Create a JavaScript Array from 1 to N?

How to Efficiently Generate an Array Containing 1...N in JavaScript

Original code:

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}
Copy after login

While this approach is straightforward, it involves an explicit loop, which may not be the most efficient option. Here are some alternatives for creating an array containing 1 through N without the loop:

ES6 Array.from() and keys() Methods

In ES6 and above, you can utilize the Array.from() method along with the keys() method.

Array.from(Array(10).keys())
// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

Shorter Version Using Spread Operator

You can make the code even more concise using the spread operator.

[...Array(10).keys()]
// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

Starting from 1 with map Function

To start the array from 1 instead of 0, you can use the map function with an object having a length property.

Array.from({length: 10}, (_, i) => i + 1)
// => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy after login

These alternatives provide more efficient ways to create an array containing a range of numbers without the need for explicit loops.

The above is the detailed content of What's the Most Efficient Way to Create a JavaScript Array from 1 to N?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template