How to create an array containing 1…N

后端 未结 30 1926
旧时难觅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:48

    It seems the only flavor not currently in this rather complete list of answers is one featuring a generator; so to remedy that:

    const gen = N => [...(function*(){let i=0;while(i

    which can be used thus:

    gen(4) // [0,1,2,3]
    

    The nice thing about this is you don't just have to increment... To take inspiration from the answer @igor-shubin gave, you could create an array of randoms very easily:

    const gen = N => [...(function*(){let i=0;
      while(i++

    And rather than something lengthy operationally expensive like:

    const slow = N => new Array(N).join().split(',').map((e,i)=>i*5)
    // [0,5,10,15,...]
    

    you could instead do:

    const fast = N => [...(function*(){let i=0;while(i++

提交回复
热议问题