Creating Arrays with Ranging Values in JavaScript
Programmers often encounter the need to create arrays containing a range of values. A common approach involves a loop that iteratively adds each element to the array. However, is there a more concise and efficient method without using a loop?
In ES6, JavaScript introduced two key methods for solving this issue: Array.from() and keys(). Using Array.from(), one can convert an iterable object into an array. The keys() method returns an iterator for the keys of a given object. Combining these methods, you can achieve array creation with a range of values.
Solution Using Array.from() and keys()
Array.from(Array(10).keys()) // Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The above approach leverages the fact that Array(n) creates an array of length n, filled initially with undefined values. By using keys() on this array, we obtain an iterable of the array's keys, which correspond to the desired range of numbers. Array.from() then converts this iterable into an array.
Shorter Version with Spread Operator
[...Array(10).keys()] // Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The spread operator (...) allows you to expand an iterable into its individual elements. Thus, the shorter version of the previous solution uses the spread operator to achieve the same result.
Starting from 1
To start the range from 1 instead of 0, you can use the map() function along with Array.from():
Array.from({length: 10}, (_, i) => i + 1) // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The map() function transforms each element in the iterable. Here, each element is a value passed from the original array, represented by the placeholder _, and its corresponding index, represented by i. The transformation adds 1 to the index, starting the range from 1. The result is then passed to Array.from() to create the final array.
The above is the detailed content of How Can I Efficiently Create Arrays with Ranging Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!