How to create an array containing 1…N

后端 未结 30 1533
旧时难觅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 02:03

    Final Summary report .. Drrruummm Rolll -

    This is the shortest code to generate an Array of size N (here 10) without using ES6. Cocco's version above is close but not the shortest.

    (function(n){for(a=[];n--;a[n]=n+1);return a})(10)
    

    But the undisputed winner of this Code golf(competition to solve a particular problem in the fewest bytes of source code) is Niko Ruotsalainen . Using Array Constructor and ES6 spread operator . (Most of the ES6 syntax is valid typeScript, but following is not. So be judicious while using it)

    [...Array(10).keys()]
    

提交回复
热议问题