javascript - Create Simple Dynamic Array

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

    Some of us are referring to use from which is not good at the performance:

    function getArrayViaFrom(input) {
      console.time('Execution Time');
      let output = Array.from(Array(input), (value, i) => (i + 1).toString())
      console.timeEnd('Execution Time');
    
      return output;
    }
    
    function getArrayViaFor(input) {
      console.time('Execution Time 1');
      var output = [];
      for (var i = 1; i <= input; i++) {
        output.push(i.toString());
      }
      console.timeEnd('Execution Time 1');
    
      return output;
    }
    
    console.log(getArrayViaFrom(10)) // Takes 10x more than for that is 0.220ms
    console.log(getArrayViaFor(10))  // Takes 10x less than From that is 0.020ms

提交回复
热议问题