javascript - Create Simple Dynamic Array

前端 未结 16 1878
刺人心
刺人心 2020-12-14 06:53

What\'s the most efficient way to create this simple array dynamically.

var arr = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];
<         


        
相关标签:
16条回答
  • 2020-12-14 07:21

    A little late to this game, but there is REALLY cool stuff you can do with ES6 these days.

    You can now fill an array of dynamic length with random numbers in one line of code!

    [...Array(10).keys()].map(() => Math.floor(Math.random() * 100))
    
    0 讨论(0)
  • 2020-12-14 07:21

    I had a similar problem and a solution I found (forgot where I found it) is this:

    Array.from(Array(mynumber), (val, index) => index + 1)

    0 讨论(0)
  • 2020-12-14 07:23

    Sounds like you just want to construct an array that contains the string versions of the integer values. A simple approach:

    var arr = [];
    for (var i = 1; i <= mynumber; i++) arr.push(""+i);
    

    For a more interesting version you could do a generator...

    function tail(i, maxval) {
        return [i].concat(i < maxval ? tail(i+1, maxval) : []);
    }
    
    var arr = tail(1, mynumber);
    
    0 讨论(0)
  • 2020-12-14 07:25

    If you are asking whether there is a built in Pythonic range-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.

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