How to create an array containing 1…N

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

    Arrays innately manage their lengths. As they are traversed, their indexes can be held in memory and referenced at that point. If a random index needs to be known, the indexOf method can be used.


    This said, for your needs you may just want to declare an array of a certain size:

    var foo = new Array(N);   // where N is a positive integer
    
    /* this will create an array of size, N, primarily for memory allocation, 
       but does not create any defined values
    
       foo.length                                // size of Array
       foo[ Math.floor(foo.length/2) ] = 'value' // places value in the middle of the array
    */
    


    ES6

    Spread

    Making use of the spread operator (...) and keys method, enables you to create a temporary array of size N to produce the indexes, and then a new array that can be assigned to your variable:

    var foo = [ ...Array(N).keys() ];
    

    Fill/Map

    You can first create the size of the array you need, fill it with undefined and then create a new array using map, which sets each element to the index.

    var foo = Array(N).fill().map((v,i)=>i);
    

    Array.from

    This should be initializing to length of size N and populating the array in one pass.

    Array.from({ length: N }, (v, i) => i)
    



    In lieu of the comments and confusion, if you really wanted to capture the values from 1..N in the above examples, there are a couple options:

    1. if the index is available, you can simply increment it by one (e.g., ++i).
    2. in cases where index is not used -- and possibly a more efficient way -- is to create your array but make N represent N+1, then shift off the front.

      So if you desire 100 numbers:

      let arr; (arr=[ ...Array(101).keys() ]).shift()
      




提交回复
热议问题