JavaScript - Nuances of myArray.forEach vs for loop

后端 未结 3 1499
梦谈多话
梦谈多话 2020-11-29 17:58

I\'ve seen plenty of questions that suggest using:

for (var i = 0; i < myArray.length; i++){ /* ... */ }

instead of:

for         


        
3条回答
  •  無奈伤痛
    2020-11-29 18:51

    You can use your custom foreach function which will perform much better then Array.forEach

    You should add this once to your code. This will add new function to the Array.

    function foreach(fn) {
        var arr = this;
        var len = arr.length;
        for(var i=0; i

    Then you can use it anywhere like the Array.forEach

    [1,2,3].customForEach(function(val, i){
    
    });
    

    The only difference it is 3 times faster. https://jsperf.com/native-arr-foreach-vs-custom-foreach

    UPDATE: In new Chrome version the performance of .forEach() was improved. However, the solution can give the additional performance in other browsers.

提交回复
热议问题