You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes we might need to create an array of `n` length like `[0, 1, 2, ..., n-1]`. We can do this easily using ES6 [Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) like:
76
+
77
+
```js
78
+
[...Array(n).keys()];
79
+
```
80
+
81
+
This is a general version. If you need an array of length `10`, then you can set it like:
82
+
83
+
```js
84
+
[...Array(10).keys()];
85
+
// Result => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
86
+
```
87
+
88
+
### Brief explanation
89
+
90
+
1.`Array(10)` create an empty array of length `10` like `[,,,...]` where value of any index from 0-9 is `undefined`.
91
+
2.`Array(10).keys()` this returns a new **Array Iterator** object that contains the keys for each index in the array.
92
+
93
+
```js
94
+
var array1 =Array(3);
95
+
var iterator =array1.keys();
96
+
97
+
for (let key of iterator) {
98
+
console.log(key); // expected output: 0 1 2
99
+
}
100
+
```
101
+
102
+
3.`[...Array(10).keys()]`this creates a new, shallow-copied `Array` instance from `Array(10).keys()` iterable object.
103
+
104
+
### Bonus Trick
105
+
106
+
If you want the array to start from `1` and end with`n` here like `[1, 2, 3, ..., n]` instead of`[0, 1, 2, ..., n-1]`, then you can do like this:
0 commit comments