How to create an array containing 1…N

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

    In ES6:

    Array.from({length: 1000}, (_, i) => i).slice(1);
    

    or better yet (without the extra variable _ and without the extra slice call):

    Array.from({length:1000}, Number.call, i => i + 1)
    

    Or for slightly faster results, you can use Uint8Array, if your list is shorter than 256 results (or you can use the other Uint lists depending on how short the list is, like Uint16 for a max number of 65535, or Uint32 for a max of 4294967295 etc. Officially, these typed arrays were only added in ES6 though). For example:

    Uint8Array.from({length:10}, Number.call, i => i + 1)
    

    ES5:

    Array.apply(0, {length: 1000}).map(function(){return arguments[1]+1});
    

    Alternatively, in ES5, for the map function (like second parameter to the Array.from function in ES6 above), you can use Number.call

    Array.apply(0,{length:1000}).map(Number.call,Number).slice(1)
    

    Or, if you're against the .slice here also, you can do the ES5 equivalent of the above (from ES6), like:

    Array.apply(0,{length:1000}).map(Number.call, Function("i","return i+1"))
    

提交回复
热议问题