不要循环比较反对我当array.length检查array.length每一次? [英] Do loops check the array.length every time when comparing i against array.length?

查看:142
本文介绍了不要循环比较反对我当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;我++)。对于微优化,这是有效的数组的长度存储在临时变量(参见:<一href=\"http://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript\">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++;
}

这篇关于不要循环比较反对我当array.length检查array.length每一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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