Do loops check the array.length every time when comparing i against array.length?

前端 未结 5 1529
一向
一向 2020-11-30 07:44

I was browsing around and I found this:

var i, len;
for(i = 0, len = array.length; i < len; i++) {  
   //...
}

My first thoughts are:

5条回答
  •  遥遥无期
    2020-11-30 08:17

    A loop consisting of three parts is executed as follows:

    for (A; B; C)
    
    A - Executed before the enumeration
    B - condition to test
    C - expression after each enumeration (so, not if B evaluated to false)
    

    So, yes: The .length property of an array is checked at each enumeration if it's constructed as for(var i=0; i. For micro-optimisation, it's efficient to store the length of an array in a temporary variable (see also: What's the fastest way to loop through an array in JavaScript?).

    Equivalent to for (var i=0; i:

    var i = 0;
    while (i < array.length) {
        ...
        i++;
    }
    

提交回复
热议问题