简体   繁体   English

使用条件退出 for 循环

[英]Exiting a for loop using a conditional

I had a problem which was that I was using a loop eg我有一个问题是我使用了一个循环,例如

for(let i=0; i<10; i++){
if(i === 3){
    // go to the next iteration of the loop
}
console.log(i)

} }

and I was struggling to see how to get to the next iteration.我正在努力了解如何进行下一次迭代。 I tried a "return" statement but this came up with the error "illegal return statement" and having done a quick search on the forums the answer was not obvious, so I thought I'd log it here so that next time I can find it easier.我尝试了“return”语句,但出现了“非法返回语句”错误,并且在论坛上进行了快速搜索,答案并不明显,所以我想我会在这里记录,以便下次我可以找到它更容易。

查看了 MDN 文档后,IU 真正想要的是一个“继续”语句,它使块中的其余代码短路并直接进入下一次迭代。

You just have to write a continue keyword in for loop to goto next loop,你只需要在 for 循环中写一个 continue 关键字来转到下一个循环,

for(let i=0; i<10; i++){
    if(i === 3){
        continue;
    }
    console.log(i)
}

Note: choose let judiciously, it can also be used with var as it is having a function scope.注意:明智地选择let ,它也可以与var一起使用,因为它具有函数作用域。

If you want to skip the rest of code in current iteration and get to next one, continue;如果您想跳过当前迭代中的其余代码并进入下一个,请continue; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue

If you want to exit loop completely, use break;如果你想完全退出循环,使用break;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM