javascript - Create Simple Dynamic Array

前端 未结 16 2027
刺人心
刺人心 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:14

    Update: micro-optimizations like this one are just not worth it, engines are so smart these days that I would advice in the 2020 to simply just go with var arr = [];.

    Here is how I would do it:

    var mynumber = 10;
    var arr = new Array(mynumber);
    
    for (var i = 0; i < mynumber; i++) {
        arr[i] = (i + 1).toString();
    }
    

    My answer is pretty much the same of everyone, but note that I did something different:

    • It is better if you specify the array length and don't force it to expand every time

    So I created the array with new Array(mynumber);

提交回复
热议问题