为什么 JavaScript 中的“continue”语句不好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11728757/
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
Why are "continue" statements bad in JavaScript?
提问by twiz
In the book Javascript: The Good Partsby Douglas Crockford, this is all the author has to say about the continue Statement:
在道格拉斯·克罗克福德 (Douglas Crockford)的《Javascript: The Good Parts》一书中,这就是作者对 continue 语句的全部内容:
The
continue
statement jumps to the top of the loop. I have never seen a piece of code that was not improved by refactoring it to remove thecontinue
statement.
该
continue
语句跳转到循环的顶部。我从来没有见过一段代码不是通过重构它来删除continue
语句而得到改进的。
This really confuses me. I know Crockford has some very opinionated views on JavaScript, but this just sounds entirely wrong to me.
这真的让我很困惑。我知道 Crockford 对 JavaScript 有一些非常固执的观点,但这对我来说听起来完全错误。
First of all, continue
does more than just jump to the top of a loop. By default, it also progresses to the next iteration. So isn't Crockford's statement just completely false information?
首先,continue
不仅仅是跳到循环的顶部。默认情况下,它也会进入下一次迭代。那么克罗克福德的声明不就是完全虚假的信息吗?
More importantly, I do not entirely understand why continue
would even be considered to be bad. This post provides what seems to be the general assumption:
Why is continue inside a loop a bad idea?
更重要的是,我不完全明白为什么continue
甚至会被认为是坏的。这篇文章提供了似乎是一般假设:
为什么在循环内继续是个坏主意?
Although I understand how continue
may make code difficult to read in certain instances, I think it is just as likely that it can make code more readable. For instance:
虽然我理解continue
在某些情况下如何使代码难以阅读,但我认为它同样有可能使代码更具可读性。例如:
var someArray=['blah',5,'stuff',7];
for(var i=0;i<someArray.length;i++){
if(typeof someArray[i]==='number'){
for(var j=0;j<someArray[i];j++){
console.log(j);
}
}
}
This could be refactored into:
这可以重构为:
var someArray=['blah',5,'stuff',7];
for(var i=0;i<someArray.length;i++){
if(typeof someArray[i]!=='number'){
continue;
}
for(var j=0;j<someArray[i];j++){
console.log(j);
}
}
continue
isn't particularly beneficial in this specific example, but it does demonstrate the fact that it reduces the nesting depth. In more complex code, this could potentially increase readability.
continue
在这个特定的例子中并不是特别有益,但它确实证明了它减少了嵌套深度的事实。在更复杂的代码中,这可能会提高可读性。
Crockford provides no explanation as to why continue
should not be used, so is there some deeper significance behind this opinion that I am missing?
克罗克福德没有解释为什么continue
不应该使用,所以我遗漏的这个意见背后是否有更深层次的意义?
回答by egrunin
The statement is ridiculous. continue
can be abused, but it often helpsreadability.
声明很可笑。continue
可以被滥用,但它通常有助于可读性。
Typical use:
典型用途:
for (somecondition)
{
if (!firsttest) continue;
some_provisional_work_that_is_almost_always_needed();
if (!further_tests()) continue;
do_expensive_operation();
}
The goal is to avoid 'lasagna' code, where you have deeply nested conditionals.
目标是避免“烤宽面条”代码,在那里你有很深的嵌套条件。
Edited to add:
编辑添加:
Yes, this is ultimately subjective. Here's my metric for deciding.
是的,这最终是主观的。这是我的决定指标。
Edited one last time:
最后一次编辑:
This example is too simple, of course, and you can always replace nested conditionals with function calls. But then you may have to pass data into the nested functions by reference, which can create refactoring problems at least as bad as the ones you're trying to avoid.
当然,这个例子太简单了,你总是可以用函数调用替换嵌套的条件。但是,您可能必须通过引用将数据传递到嵌套函数中,这可能会产生至少与您试图避免的问题一样严重的重构问题。
回答by jJ'
I am personally on the other side than the majority here. The problem is usually not with the shown continue
patterns, but with more deeply nested ones, where possible code paths may become hard to see.
我个人站在另一边,而不是这里的大多数人。问题通常不在于显示的continue
模式,而在于更深的嵌套模式,其中可能的代码路径可能变得难以看到。
But even your example with one continue
does not show improvement in my opinion that is justifiable. From my experience a few continue
statements are a nightmare to refactorlater (even for static languages better suited for automated refactoring like Java, especially when someone later puts there break
too).
但即使是你的例子continue
也没有显示出在我看来是合理的改进。根据我的经验,一些continue
语句是以后重构的噩梦(即使对于像 Java 这样更适合自动重构的静态语言,尤其是当后来有人也把它放在那里时break
)。
Thus, I would add a comment to the quote you gave:
因此,我会在您给出的引文中添加评论:
Refactoring to remove
continue
statement inreases your further ability to refactor.
重构以删除
continue
语句会增强您进一步重构的能力。
And inner loops are really good candidated for e.g. extract function. Such refactoring is done when the inner loop becomes complex and then continue
may make it painful.
并且内循环非常适合用于例如提取功能。这种重构是在内部循环变得复杂时完成的,然后continue
可能会使其变得痛苦。
These are my honest opinions after working professionally on JavaScript projects in a team, there rules that Douglas Crockford talks about really show their merits.
这些是我在团队中专业从事 JavaScript 项目后的诚实意见,Douglas Crockford 谈论的规则确实显示了它们的优点。
回答by Tom Lucas
Douglas Crockford may feel this way because he doesn't believe in assignment within a conditional. In fact, his program JSlint doesn't even let you do it, even though Javascript does. He would never write:
道格拉斯·克罗克福德(Douglas Crockford)可能会有这种感觉,因为他不相信有条件的分配。事实上,他的程序 JSlint 甚至不允许你这样做,即使 Javascript 允许。他永远不会写:
Example 1
示例 1
while (rec = getrec())
{
if (condition1(rec))
continue;
doSomething(rec);
}
but, I'm guessing he wouldwrite something like:
但是,我猜他会写这样的东西:
Example 2
示例 2
rec = getrec();
while (rec)
{
if (!condition(rec))
doSomething(rec);
rec = getrec();
}
Both of these work, but if you accidentally mix these styles you get an infinite loop:
这两个都有效,但如果你不小心混合了这些样式,你会得到一个无限循环:
Example 3
示例 3
rec = getrec();
while (rec)
{
if (condition1(rec))
continue;
rec = getrec();
}
This could be part of why he doesn't like continues.
这可能是他不喜欢继续的部分原因。
回答by shauryashaurya
Actually, from all the analysis it seems:
实际上,从所有的分析来看:
- If you have shallow loops - feel free to use continue iff it improves readability (also, there maybe some performance gains?).
- If you have deep nested loops (which means you already have a hairball to untangle when you re-factor) avoiding continue may prove to be beneficial from a code reliability standpoint.
- 如果您有浅循环 - 随意使用 continue 如果它提高了可读性(另外,可能会有一些性能提升?)。
- 如果您有深层嵌套循环(这意味着您在重构时已经有一个毛球需要解开),从代码可靠性的角度来看,避免 continue 可能会被证明是有益的。
In defense of Douglas Crokford, I feel that his recommendations tend to lean towards defensive programming, which, in all honesty seems like a good approach for 'idiot-proofing' the code in the enterprise.
在为 Douglas Crokford 辩护时,我觉得他的建议倾向于防御性编程,老实说,这似乎是企业中“防白痴”代码的好方法。
回答by Travis J
Continue is an extremely useful tool for saving computation cycles in algorithms. Sure, it can be improperly used but so can every other keyword or approach. When striving for performance, it can be useful to take an inverse approach to path divergence with a conditional statement. A continue can facilitate the inverse by allowing less efficient paths to be skipped when possible.
Continue 是一个非常有用的工具,用于节省算法中的计算周期。当然,它可能会被不当使用,但其他所有关键字或方法也可能会被不当使用。在追求性能时,使用条件语句对路径发散采取逆向方法会很有用。continue 可以通过允许在可能的情况下跳过效率较低的路径来促进反向操作。
回答by Brock B.
Personally, I have never heard anything bad about using the continue statement. It is true that it could (most of the time) be easily avoided, but there is no reason to notuse it. I find that loops can be a lot cleaner looking and more readable with continue statements in place.
就个人而言,我从未听说过使用 continue 语句有什么不好的地方。确实,它可以(大部分时间)很容易避免,但没有理由不使用它。我发现使用 continue 语句,循环可以看起来更清晰,可读性更强。