每次将 i 与 array.length 进行比较时,循环都会检查 array.length 吗? [英] Do loops check the array.length every time when comparing i against array.length?

查看:39
本文介绍了每次将 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++;
}

这篇关于每次将 i 与 array.length 进行比较时,循环都会检查 array.length 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆