不要循环比较反对我当array.length检查array.length每一次?

问题描述:

我在浏览周围,我found这

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

我的第一个想法是:

My first thoughts are:


  • 他为什么这样做? (它必须是出于某种原因越好)

  • 是否值得呢? (我想是的,否则为什么他会做这种方式?)

做正常的循环(不缓存长度的)检查 array.length 每次

Do normal loops (the ones that don't cache the length) check the array.length each time?

由三部分组成一个循环的执行过程如下:

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)

所以,是的:数组的。长度属性在每个枚举如果它的构造为(VAR检查i = 0; I&LT ; array.length;我++)。对于微优化,这是有效的数组的长度存储在临时变量(参见:What's通过在JavaScript中?)。

So, yes: The .length property of an array is checked at each enumeration if it's constructed as for(var i=0; i<array.length; 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?).

等同于为(VAR I = 0; I&LT; array.length,我++){...}

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