How to create an array containing 1…N

后端 未结 30 1545
旧时难觅i
旧时难觅i 2020-11-22 01:04

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

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:41

    Multiple ways using ES6

    Using spread operator (...) and keys method

    [ ...Array(N).keys() ].map( i => i+1);
    

    Fill/Map

    Array(N).fill().map((_, i) => i+1);
    

    Array.from

    Array.from(Array(N), (_, i) => i+1)
    

    Array.from and { length: N } hack

    Array.from({ length: N }, (_, i) => i+1)
    

    Note about generalised form

    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)
    

    Examples:

    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

    Example showcasing all the forms

    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)

    More generic example with custom initialiser function 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)

提交回复
热议问题