哪个更快的for循环或foreach?

时间:2016-08-25 05:46:19

标签: javascript performance for-loop foreach

让我们在一个数组上,

方法1:



var array = ["a","a","a","a","a"];
  for(var i=1; i<=array.length; i++)
      array[i-1] += i;
  console.log(array);
&#13;
&#13;
&#13;

方法2:

  var array = ["a","a","a","a","a"];
  var i = 1;
  array.forEach(function(){
      array[i-1] += i;
      i++;
   });
   console.log(array);

array 上的两个方法产生相同的结果,即:

[&#34; A1&#34;&#34; A2&#34;&#34; A3&#34;&#34; A4&#34;&#34; A5&#34;] < / p>

但是 1)哪种方法最快?
2)有没有其他更快的方法来做同样的转换[&#34; a&#34;,&#34; a&#34;,&#34; a&#34;&#34; a&# 34;,&#34; a&#34;]到[&#34; a1&#34;,&#34; a2&#34;,&#34; a3&#34;,&#34; a4&#34;, &#34; A5&#34;?]
3)有没有办法知道两个代码片段的时间?请不要太技术化......

0 个答案:

没有答案