每次将 i 与 array.length 进行比较时,循环都会检查 array.length 吗?
问题描述:
我四处浏览,我发现这个:
var i, len;
for(i = 0, len = array.length; i < len; i++) {
//...
}
我的第一个想法是:
- 他为什么这样做?(由于某种原因它必须更好)
- 值得吗?(我想是的,否则他为什么会这样做?)
普通循环(不缓存长度的循环)是否每次都检查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)
所以,是的:如果数组的 .length
属性构造为 for(var i=0; i<array.length; i++)代码>.对于微优化,将数组的长度存储在临时变量中是有效的(另请参阅:在 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?).
等价于for (var i=0; i
var i = 0;
while (i < array.length) {
...
i++;
}