jQuery for 循环而不是 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7168995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:29:52  来源:igfitidea点击:

For loop instead of while loop

jquery

提问by Randomblue

Reading through the jQuery source I stumbled upon the following piece of code (available here):

阅读 jQuery 源代码时,我偶然发现了以下代码段(可在此处获得):

for (; i < length;) {
    if (callback.apply(object[i++], args) === false) {
        break;
    }
}

Why is a forloop used here instead of a whileloop?

为什么for这里使用循环而不是while循环?

采纳答案by aroth

I vote for someone having an affinity for bad coding style. That's the only explanation I can see for both the forloop and the i++being placed inside of an array subscript. I think this would be better:

我投票给那些对糟糕的编码风格有亲和力的人。对于for循环和i++放置在数组下标内,这是我能看到的唯一解释。我认为这样会更好:

while (i < length && callback.apply(object[i], args)) {
    i++;
}

Or if you happen to feel that the ===operator in the original example has value, then:

或者如果你碰巧觉得===原始例子中的操作符有价值,那么:

while (i < length && callback.apply(object[i], args) !== false) {
    i++;
}

Another possible reason for doing this may have been as a performance optimization. Although this quick benchmarkthat I put together seems to disprove that theory. On Windows the whileloop above is 20% faster than the original forloop in Chrome, in IE and Firefox both loops perform the same. On OS X the forloop has a 10% advantage in Firefox, there is no difference between the two in Chrome, and Safari prefers the whileloop by 6%.

这样做的另一个可能原因可能是作为性能优化。虽然我放在一起的这个快速基准似乎反驳了这个理论。在 Windows 上,while上面的循环比forChrome 中的原始循环快 20% ,在 IE 和 Firefox 中,这两个循环执行相同。在 OS X 上,for循环在 Firefox 中具有 10% 的优势,在 Chrome 中两者之间没有区别,而 Safari 则更喜欢while循环 6%。

So from a performance standpoint it's a wash. If anything then judging by market share you would probably want to optimize for Chrome on Windows before optimizing for Firefox on Mac, in which case the whileloop would be preferred.

所以从性能的角度来看,这是一种洗礼。如果有的话,那么从市场份额来看,您可能希望先针对 Windows 上的 Chrome 进行优化,然后再针对 Mac 上的 Firefox 进行优化,在这种情况下,while循环将是首选。

Which says to me that it's unlikely that performance optimization played a factor with this code. And I return to my original theory that it's just an example of poor coding style making it past the code-review process.

这对我说,性能优化不太可能对这段代码产生影响。我回到我最初的理论,它只是一个糟糕的编码风格使它通过了代码过程的例子。

回答by Stephen Swensen

Probably because it was "refactored" from a for (x in obj)loop: http://james.padolsey.com/jquery/#v=1.3.2&fn=jQuery.each

可能是因为它是从for (x in obj)循环中“重构”的:http: //james.padolsey.com/jquery/#v=1.3.2&fn=jQuery.each

回答by hammar

Here is the commit that introduced this oddity.

这是引入这种奇怪之处的提交

Commit message:

提交消息:

jquery core: code reduction at $.eachand $.curCSS.

jquery 核心:代码减少$.each$.curCSS.

Snip from the diff:

从差异中剪下:

-        for ( var i = 0, length = object.length; i < length; i++ )
-          if ( callback.apply( object[ i ], args ) === false )
+        for ( ; i < length; )
+          if ( callback.apply( object[ i++ ], args ) === false )

It would appear that the author simply missed the opportunity to change the forinto a while.

看来作者只是错过了forwhile.

回答by Briguy37

First, there is never a length cost for using a forloop over a whileloop, but you get additional functionality with the forloop, so some coders just always use the for:

首先,在for循环上使用循环永远不会有长度成本while,但是您可以通过循环获得额外的功能for,因此一些编码人员总是使用for

for(;<condition>;){}
while(<condition>){}

That said, I think the purpose here may be for consistency with the surrounding code.

也就是说,我认为这里的目的可能是为了与周围的代码保持一致。

For example, here is part of the original code. As you can see, in this code you can stay in the "for" loop mode of thinking the whole time, so it feelsmore consistent:

例如,这里是原始代码的一部分。如你所见,在这段代码中,你可以一直停留在“for”循环的思考模式中,所以感觉更加一致:

if (args) {
    if (isObj) {
        for (name in object) {
            if (callback.apply(object[name], args) === false) {
                break;
            }
        }
    } else {
        for (; i < length;) {
            if (callback.apply(object[i++], args) === false) {
                break;
            }
        }
    }
}

Compare this to replacing the second loop with a while. When you read this code, you have to switch from the "for" loop mode of thinking to the "while" loop mode of thinking. Now I don't know about you, but I find it slightly faster for my eyes to switch between the loop conditions above as opposed to the loop conditions below. This is because in the above case I can just concentrate on the conditions, whereas in the below case my eyes are drawn to reread the whileand the foreach time because they are different:

将此与用 a 替换第二个循环进行比较while。当你阅读这段代码时,你不得不从“for”循环思维模式切换到“while”循环思维模式。现在我不了解你,但我发现我的眼睛在上面的循环条件之间切换比下面的循环条件要快一些。这是因为在上面的情况下,我可以只关注条件,而在下面的情况下,我的眼睛每次都被吸引重新阅读 thewhile和 thefor因为它们是不同的:

if (args) {
    if (isObj) {
        for (name in object) {
            if (callback.apply(object[name], args) === false) {
                break;
            }
        }
    } else {
        while (i < length) {
            if (callback.apply(object[i++], args) === false) {
                break;
            }
        }
    }
}

回答by cmpolis

I've found that things like this occur when I rewrite things or if multiple people touch a piece of code. Can't see any particular reason for it.

我发现当我重写东西或者多人接触一段代码时会发生这样的事情。看不出有什么特别的原因。

I hope igets initialized properly above this block.

我希望在这个块上方正确初始化。

回答by shabunc

The shortest and most honest answer is pretty short "just because". There is absolutely no practical reason to do it, we don't gain any profit from such 2-smiles loop.

最短和最诚实的答案很短,“只是因为”。绝对没有实际的理由这样做,我们不会从这种 2-smiles 循环中获得任何利润。

As for aforementioned reasons, such as:

至于上述原因,例如:

  • refactoring - which is most possible, but nevertheless this is not an excuse.
  • minification considerations - which is less, less possible.
  • psychological/readability/code supporting issues - I very dubious that somebody write such code keeping in mind that a user can be confused for some code constructions and loose concentration;
  • 重构 - 这是最有可能的,但这不是借口。
  • 缩小考虑 - 这是更少,更不可能。
  • 心理/可读性/代码支持问题 - 我非常怀疑有人编写这样的代码,记住用户可能会因某些代码结构和注意力不集中而感到困惑;

well, as for these reasons - all of them definitely worth mentioning, but, to be honest, jquery code style is, well, not ideal. Sometimes there arereasons why it is so, some times, it's just a matter of fact.

好吧,至于这些原因 - 所有这些绝对值得一提,但是,说实话,jquery 代码风格并不理想。有时是有原因的,有时事实。

Production code is not always the most beautiful code. Reading production-ready, hardcore code on any language is always for good, but is not 100% about code style. Say, vim is beautiful, very powerful software, but (as for me) some purist can be surprised with it source code. Though loops stuff is ok ))))

生产代码并不总是最漂亮的代码。阅读任何语言的生产就绪、核心代码总是好的,但不是 100% 的代码风格。比如说,vim 是一个漂亮的、非常强大的软件,但是(就我而言)一些纯粹主义者可能会对它的源代码感到惊讶。虽然循环的东西是好的))))

回答by Phineas

So t will run at least once, because if you use a while loop if the logic is false it wont run. For lopp even if it is false it will run atleast once.

所以 t 至少会运行一次,因为如果你使用 while 循环,如果逻辑为假,它就不会运行。对于 lopp 即使它是假的,它也会至少运行一次。