How to create an array containing 1…N

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

    In ES6 using Array from() and keys() methods.

    Array.from(Array(10).keys())
    //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Shorter version using spread operator.

    [...Array(10).keys()]
    //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Start from 1 by passing map function to Array from(), with an object with a length property:

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

提交回复
热议问题