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); }
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]
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]
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]
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!