gpt4 book ai didi

javascript - 为什么 "continue"语句在 JavaScript 中是错误的?

转载 作者:IT王子 更新时间:2023-10-29 02:53:23 27 4
gpt4 key购买 nike

<分区>

在 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 the continue statement.

这让我很困惑。我知道 Crockford 对 JavaScript 有一些非常自以为是的观点,但这对我来说听起来完全错误。

首先,continue 不仅仅是跳转到循环的顶部。默认情况下,它还会进行到下一次迭代。那么克罗克福德的说法不就是完全错误的信息吗?

更重要的是,我不完全理解为什么 continue 甚至会被认为是坏的。这篇文章提供了似乎是一般假设的内容: Why is continue inside a loop a bad idea?

虽然我理解 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);
}
}
}

这可以重构为:

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 在此特定示例中并不是特别有用,但它确实证明了它减少了嵌套深度这一事实。在更复杂的代码中,这可能会提高可读性。

Crockford 没有解释为什么不应该使用 continue,那么我遗漏的这个观点背后是否有更深层次的意义?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com