What is the best way to do loops in JavaScript

前端 未结 9 1851
温柔的废话
温柔的废话 2020-12-13 00:35

I have stumbled into several methods of looping in JavaScript, what I like the most is:

for(var i = 0; i < a.length; i++){
    var element = a[i];
}
         


        
9条回答
  •  有刺的猬
    2020-12-13 01:08

    I don't see what the problem with using a standard for(;;) loop is. A little test

    var x;
    var a = [];
    // filling array
    var t0 = new Date().getTime();
    for( var i = 0; i < 100000; i++ ) {
        a[i] = Math.floor( Math.random()*100000 );
    }
    
    // normal loop
    var t1 = new Date().getTime();
    for( var i = 0; i < 100000; i++ ) {
        x = a[i];
    }
    
    // using length
    var t2 = new Date().getTime();
    for( var i = 0; i < a.length; i++ ) {
        x = a[i];
    }
    
    // storing length (pollution - we now have a global l as well as an i )
    var t3 = new Date().getTime();
    for( var i = 0, l = a.length; i < l; i++ ) {
        x = a[i];
    }
    
    // for in
    var t4 = new Date().getTime();
    for( var i in a ) {
        x = a[i];
    }
    
    // checked for in
    var t5 = new Date().getTime();
    for( var i in a ) {
        if (a.hasOwnProperty(i)) {
            x = a[i];
        }
    }
    
    var t6 = new Date().getTime();
    var msg = 'filling array: '+(t1-t0)+'ms\n'+
              'normal loop: '+(t2-t1)+'ms\n'+
              'using length: '+(t3-t2)+'ms\n'+
              'storing length: '+(t4-t3)+'ms\n'+
              'for in: '+(t5-t4)+'ms\n'+
              'checked for in: '+(t6-t5)+'ms';
    console.log( msg );
    

    results in:

    filling array: 227ms
    normal loop: 21ms
    using length: 26ms
    storing length: 24ms 
    for in: 154ms
    checked for in: 176ms
    

    So:- for in's take the longest, using the length property (which is a property and doesn't need to be calculated) is nearly as fast as storing it first - which is only a whisker slower than using an integer.
    AND a for() is the usual way to loop over an array, which everyone expects and understands.

    All of them add a variable to the scope they run in - i - which is a common name for this use and so shouldn't be used for other things. Storing the length first adds another var - l - to the scope, which is unnecesary

提交回复
热议问题