Does anybody have idea for easy clean way (maybe using ES6) to get
from "6" to array [1, 2, 3, 4, 5, 6]
or "2" to [1, 2]
etc.
I know I can use loop "for", but is there any shorter single-line way?
Does anybody have idea for easy clean way (maybe using ES6) to get
from "6" to array [1, 2, 3, 4, 5, 6]
or "2" to [1, 2]
etc.
I know I can use loop "for", but is there any shorter single-line way?
You can use the spread operator on the created array [...Array(n).keys()]
console.log([...Array(6).keys()])
console.log([...Array(2).keys()])
// or
console.log(Array.from(Array(6).keys(), i => i+1));
console.log(Array.from(Array(2).keys(), i => i+1));
Using Array.from()
with mapFn
console.log(Array.from({length: 6}, (_, i) => i + 1));
console.log(Array.from({length: 2}, (_, i) => i + 1));
You can use Array.from and it's callback
let range = num => Array.from({ length: num }, (_, i) => ++i)
console.log(range(6))
console.log(range(2))
console.log(range(-6))
If you add the iterator, for example, to the prototype of Number
, you could even spread numbers.
Number.prototype[Symbol.iterator] = function* () {
for (var i = 0; i < this; i++) yield i;
};
console.log([...10]);