My Profile Photo

Hao's Keeper


A blog to place memos


Javascript Create Array From 1 to N

How to create an array containing 1…N

Array.from(Array(10).keys());
// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[...Array(10).keys()]
// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[...Array(N+1).keys()].slice(1)

spread operator (…)

var foo = Array(N).fill().map((v,i)=>i);

even:

Array.from({length: 10}, (_, i) => i * 2);