I\'m looking for any alternatives to the below for creating a JavaScript array containing 1
through to N
where N
is only known at runt
...
) and keys method[ ...Array(N).keys() ].map( i => i+1);
Array(N).fill().map((_, i) => i+1);
Array.from(Array(N), (_, i) => i+1)
{ length: N }
hackArray.from({ length: N }, (_, i) => i+1)
All the forms above can produce arrays initialised to pretty much any desired values by changing i+1
to expression required (e.g. i*2
, -i
, 1+i*2
, i%2
and etc). If expression can be expressed by some function f
then the first form becomes simply
[ ...Array(N).keys() ].map(f)
Array.from({length: 5}, (v, k) => k+1);
// [1,2,3,4,5]
Since the array is initialized with undefined
on each position, the value of v
will be undefined
let demo= (N) => {
console.log(
[ ...Array(N).keys() ].map(( i) => i+1),
Array(N).fill().map((_, i) => i+1) ,
Array.from(Array(N), (_, i) => i+1),
Array.from({ length: N }, (_, i) => i+1)
)
}
demo(5)
f
i.e.[ ...Array(N).keys() ].map((i) => f(i))
or even simpler
[ ...Array(N).keys() ].map(f)
let demo= (N,f) => {
console.log(
[ ...Array(N).keys() ].map(f),
Array(N).fill().map((_, i) => f(i)) ,
Array.from(Array(N), (_, i) => f(i)),
Array.from({ length: N }, (_, i) => f(i))
)
}
demo(5, i=>2*i+1)