How to create an array containing 1…N

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

    Using ES6

    const generateArray = n => [...Array(n)].map((_, index) => index + 1);
    
    0 讨论(0)
  • 2020-11-22 01:44

    Object.keys(Array.apply(0, Array(3))).map(Number)

    Returns [0, 1, 2]. Very similar to Igor Shubin's excellent answer, but with slightly less trickery (and one character longer).

    Explanation:

    • Array(3) // [undefined × 3] Generate an array of length n=3. Unfortunately this array is almost useless to us, so we have to…
    • Array.apply(0,Array(3)) // [undefined, undefined, undefined] make the array iterable. Note: null's more common as apply's first arg but 0's shorter.
    • Object.keys(Array.apply(0,Array(3))) // ['0', '1', '2'] then get the keys of the array (works because Arrays are the typeof array is an object with indexes for keys.
    • Object.keys(Array.apply(0,Array(3))).map(Number) // [0, 1, 2] and map over the keys, converting strings to numbers.
    0 讨论(0)
  • 2020-11-22 01:45
    Array(8).fill(0).map(Number.call, Number)
    

    Stealing Igors Number.call trick but using fill() to shorten slightly. Only works with ES6 and above.

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

    Using ES2015/ES6 spread operator

    [...Array(10)].map((_, i) => i + 1)
    

    console.log([...Array(10)].map((_, i) => i + 1))

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

    Use the very popular Underscore _.range method

    // _.range([start], stop, [step])
    
    _.range(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    _.range(1, 11); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    _.range(0, 30, 5); // => [0, 5, 10, 15, 20, 25]
    _.range(0, -10, -1); //  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    _.range(0); // => []
    
    0 讨论(0)
  • If you happen to be using d3.js in your app as I am, D3 provides a helper function that does this for you.

    So to get an array from 0 to 4, it's as easy as:

    d3.range(5)
    [0, 1, 2, 3, 4]
    

    and to get an array from 1 to 5, as you were requesting:

    d3.range(1, 5+1)
    [1, 2, 3, 4, 5]
    

    Check out this tutorial for more info.

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