How to create an array containing 1…N

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

    Using new Array methods and => function syntax from ES6 standard (only Firefox at the time of writing).

    By filling holes with undefined:

    Array(N).fill().map((_, i) => i + 1);
    

    Array.from turns "holes" into undefined so Array.map works as expected:

    Array.from(Array(5)).map((_, i) => i + 1)
    
    0 讨论(0)
  • 2020-11-22 01:41

    In ES6 using Array from() and keys() methods.

    Array.from(Array(10).keys())
    //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Shorter version using spread operator.

    [...Array(10).keys()]
    //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Start from 1 by passing map function to Array from(), with an object with a length property:

    Array.from({length: 10}, (_, i) => i + 1)
    //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    0 讨论(0)
  • 2020-11-22 01:41

    Multiple ways using ES6

    Using spread operator (...) and keys method

    [ ...Array(N).keys() ].map( i => i+1);
    

    Fill/Map

    Array(N).fill().map((_, i) => i+1);
    

    Array.from

    Array.from(Array(N), (_, i) => i+1)
    

    Array.from and { length: N } hack

    Array.from({ length: N }, (_, i) => i+1)
    

    Note about generalised form

    All the forms above can produce arrays initialised to pretty much any desired values by changing i+1 to expression required (e.g. i*2, -i, 1+i*2, i%2 and etc). If expression can be expressed by some function f then the first form becomes simply

    [ ...Array(N).keys() ].map(f)
    

    Examples:

    Array.from({length: 5}, (v, k) => k+1); 
    // [1,2,3,4,5]
    

    Since the array is initialized with undefined on each position, the value of v will be undefined

    Example showcasing all the forms

    let demo= (N) => {
      console.log(
        [ ...Array(N).keys() ].map(( i) => i+1),
        Array(N).fill().map((_, i) => i+1) ,
        Array.from(Array(N), (_, i) => i+1),
        Array.from({ length: N }, (_, i) => i+1)
      )
    }
    
    demo(5)

    More generic example with custom initialiser function f i.e.

    [ ...Array(N).keys() ].map((i) => f(i))
    

    or even simpler

    [ ...Array(N).keys() ].map(f)
    

    let demo= (N,f) => {
      console.log(
        [ ...Array(N).keys() ].map(f),
        Array(N).fill().map((_, i) => f(i)) ,
        Array.from(Array(N), (_, i) => f(i)),
        Array.from({ length: N }, (_, i) => f(i))
      )
    }
    
    demo(5, i=>2*i+1)

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

    the fastest way to fill an Array in v8 is:

    [...Array(5)].map((_,i) => i);
    

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

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

    You can use this:

    new Array(/*any number which you want*/)
        .join().split(',')
        .map(function(item, index){ return ++index;})
    

    for example

    new Array(10)
        .join().split(',')
        .map(function(item, index){ return ++index;})
    

    will create following array:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    0 讨论(0)
  • 2020-11-22 01:43

    This question has a lot of complicated answers, but a simple one-liner:

    [...Array(255).keys()].map(x => x + 1)
    

    Also, although the above is short (and neat) to write, I think the following is a bit faster (for a max length of:

    127, Int8,

    255, Uint8,

    32,767, Int16,

    65,535, Uint16,

    2,147,483,647, Int32,

    4,294,967,295, Uint32.

    (based on the max integer values), also here's more on Typed Arrays):

    (new Uint8Array(255)).map(($,i) => i + 1);
    

    Although this solution is also not so ideal, because it creates two arrays, and uses the extra variable declaration "$" (not sure any way to get around that using this method). I think the following solution is the absolute fastest possible way to do this:

    for(var i = 0, arr = new Uint8Array(255); i < arr.length; i++) arr[i] = i + 1;
    

    Anytime after this statement is made, you can simple use the variable "arr" in the current scope;

    If you want to make a simple function out of it (with some basic verification):

    function range(min, max) {
        min = min && min.constructor == Number ? min : 0;
        !(max && max.constructor == Number && max > min) && // boolean statements can also be used with void return types, like a one-line if statement.
            ((max = min) & (min = 0));  //if there is a "max" argument specified, then first check if its a number and if its graeter than min: if so, stay the same; if not, then consider it as if there is no "max" in the first place, and "max" becomes "min" (and min becomes 0 by default)
    
        for(var i = 0, arr = new (
            max < 128 ? Int8Array : 
            max < 256 ? Uint8Array :
            max < 32768 ? Int16Array : 
            max < 65536 ? Uint16Array :
            max < 2147483648 ? Int32Array :
            max < 4294967296 ? Uint32Array : 
            Array
        )(max - min); i < arr.length; i++) arr[i] = i + min;
        return arr;
    }
    
    
    
    //and you can loop through it easily using array methods if you want
    range(1,11).forEach(x => console.log(x));
    
    //or if you're used to pythons `for...in` you can do a similar thing with `for...of` if you want the individual values:
    for(i of range(2020,2025)) console.log(i);
    
    //or if you really want to use `for..in`, you can, but then you will only be accessing the keys:
    
    for(k in range(25,30)) console.log(k);
    
    console.log(
        range(1,128).constructor.name,
        range(200).constructor.name,
        range(400,900).constructor.name,
        range(33333).constructor.name,
        range(823, 100000).constructor.name,
        range(10,4) // when the "min" argument is greater than the "max", then it just considers it as if there is no "max", and the new max becomes "min", and "min" becomes 0, as if "max" was never even written
    );


    so, with the above function, the above super-slow "simple one-liner" becomes the super-fast, even-shorter:

    range(1,14000);
    
    0 讨论(0)
提交回复
热议问题