How to use Spread Operator In Javascript
We can also use Spread Operator to create an array containing 1…N numbers. We use Array() constructor to create a new array of length N, and then use keys() method to get an iterator over the indices of the array. Then spread the iterator into an array using the spread operator (…) and map each element of the resulting array to its corresponding index value plus 1.
Example: In this example, we are using Spread Operator.
function createArray(N) {
return [...Array(N).keys()].map(i => i + 1);
}
let N = 12;
let arr = createArray(N);
console.log(arr);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
How to create an array containing 1…N numbers in JavaScript ?
In this article, we will see how to create an array containing 1. . . N numbers using JavaScript. We can create an array by using different methods.
There are some methods to create an array containing 1…N numbers, which are given below:
Table of Content
- Using for Loop
- Using Spread Operator
- Using from() Method
- Using third-party library
- Using a Generator Function