How to create an array containing 1…N

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

    This is probably the fastest way to generate an array of numbers

    Shortest

    var a=[],b=N;while(b--)a[b]=b+1;
    

    Inline

    var arr=(function(a,b){while(a--)b[a]=a;return b})(10,[]);
    //arr=[0,1,2,3,4,5,6,7,8,9]
    

    If you want to start from 1

    var arr=(function(a,b){while(a--)b[a]=a+1;return b})(10,[]);
    //arr=[1,2,3,4,5,6,7,8,9,10]
    

    Want a function?

    function range(a,b,c){c=[];while(a--)c[a]=a+b;return c}; //length,start,placeholder
    var arr=range(10,5);
    //arr=[5,6,7,8,9,10,11,12,13,14]
    

    WHY?

    1. while is the fastest loop

    2. Direct setting is faster than push

    3. [] is faster than new Array(10)

    4. it's short... look the first code. then look at all other functions in here.

    If you like can't live without for

    for(var a=[],b=7;b>0;a[--b]=b+1); //a=[1,2,3,4,5,6,7]
    

    or

    for(var a=[],b=7;b--;a[b]=b+1); //a=[1,2,3,4,5,6,7]
    

提交回复
热议问题