How to create an array containing 1…N

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

    Using new Array methods and => function syntax from ES6 standard (only Firefox at the time of writing).

    By filling holes with undefined:

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

    Array.from turns "holes" into undefined so Array.map works as expected:

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

提交回复
热议问题