JavaScript退出for循环而不返回

我有一个循环,我想退出; 喜欢这个:

function MyFunction() { for (var i = 0; i < SomeCondition; i++) { if (i === SomeOtherCondition) { // Do some work here return false; } } SomeOtherFunction(); SomeOtherFunction2(); } 

问题是,在Do some work here语句之后,我想退出for循环,但是仍然执行SomeOtherFunctions();

返回false语句会退出for循环,但也会退出整个函数。 我该如何解决?

谢谢。

你正在寻找break语句 。

使用中断或继续语句

 function MyFunction() { for (var i = 0; i < SomeCondition; i++) { if (i === SomeOtherCondition) { // Do some work here break; } } SomeOtherFunction(); SomeOtherFunction2(); } 

或者继续处理除条件中的条目外的项目

 function MyFunction() { for (var i = 0; i < SomeCondition; i++) { if (i != SomeOtherCondition) continue; // Do some work here } SomeOtherFunction(); SomeOtherFunction2(); } 

有几个人提出了解决scheme,这确实是最好的答案。

然而,为了完整性,我觉得我还应该补充一点,在保留return语句的同时,可以通过将if()条件的内容封装在闭包函数中来回答问题:

 function MyFunction() { for (var i = 0; i < SomeCondition; i++) { if (i === SomeOtherCondition) { function() { // Do some work here return false; }(); } } SomeOtherFunction(); SomeOtherFunction2(); } 

正如我所说,在这种情况下, break可能是一个更好的解决scheme,因为它是问题的直接答案,闭包确实引入了一些其他因素(例如更改此值,限制函数内部引入的variables的范围等)。 但是值得提供一个解决scheme,因为这是一个有价值的技术,如果不一定要在这个特定的场合使用,那么肯定会用于未来。

打破 – 整个循环。 继续 – 跳过一个循环。 所以它跳过下面的代码继续;

将我的variables设置为somecondition值是一个好方法?

 for (var i=0; i<SomeCondition; i++) { if (data[i]===true) { //do stuff i=SomeCondition; } } 

好吧,也许这是一个老话题,但在阅读所有的答案后,我想知道为什么没有人build议使用while循环呢?

我想在JavaScript中你可以打破一个for循环(你不能在许多其他语言中做,或者被认为是一个坏习惯),但我仍然会使用for循环只为你想迭代循环固定数量的情况倍。

这将是我的build议:

 function MyFunction() { var i = 0, breakLoop = false; while (i < SomeCondition && !breakLoop) { if (i === SomeOtherCondition) { breakLoop = true; } i++; } SomeOtherFunction(); SomeOtherFunction2(); }