How to create an array containing 1…N

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

    If I get what you are after, you want an array of numbers 1..n that you can later loop through.

    If this is all you need, can you do this instead?

    var foo = new Array(45); // create an empty array with length 45
    

    then when you want to use it... (un-optimized, just for example)

    for(var i = 0; i < foo.length; i++){
      document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 
    }
    

    e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

    See it in action here: http://jsfiddle.net/3kcvm/

    0 讨论(0)
  • 2020-11-22 01:54

    with ES6 you can do:

    // `n` is the size you want to initialize your array
    // `null` is what the array will be filled with (can be any other value)
    Array(n).fill(null)
    
    0 讨论(0)
  • 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()
      




    0 讨论(0)
  • 2020-11-22 01:57

    the new way to filling Array is:

    const array = [...Array(5).keys()]
    console.log(array)

    result will be: [0, 1, 2, 3, 4]

    0 讨论(0)
  • 2020-11-22 01:59

    Just another ES6 version.

    By making use of Array.from second optional argument:

    Array.from(arrayLike[, mapFn[, thisArg]])

    We can build the numbered array from the empty Array(10) positions:

    Array.from(Array(10), (_, i) => i)
    

    var arr = Array.from(Array(10), (_, i) => i);
    document.write(arr);

    0 讨论(0)
  • 2020-11-22 01:59

    Iterable version using a generator function that doesn't modify Number.prototype.

    function sequence(max, step = 1) {
      return {
        [Symbol.iterator]: function* () {
          for (let i = 1; i <= max; i += step) yield i
        }
      }
    }
    
    console.log([...sequence(10)])

    0 讨论(0)
提交回复
热议问题