0
我的问题是:如何通过被调用的函数触发break;
或continue;
循环?事情是,我不想在循环中嵌套所有可能的条件以避免代码复杂性。我曾想过一些伪例如:函数调用中断或继续循环
var someObjects = [...] //array with some js objects
for (var i = 0; i < someObjects.length; i++) {
var element = someObjects[i];
doSomething(element);
}
function doSomething(object) {
//some code here
if (somethingIsDefined) {
doSomethingElse(object);
}
}
function doSomethingElse(anotherObject) {
//some more code here
if (somethingMatches) {
//here i would like to break the most upper loop
}
}
//someObjects will be processed
我知道,这将是可能引入例如布尔变量和内环路检查它是否是真的还是假的,并取决于,break;
或continue;
。
但是,即使它只是一条线,也会增加嵌套。你看到任何可能的解决方案?
你可以设置一个全局布尔等于假,将其设置为true在你的函数,并检查每个迭代如果布尔值为true。 – AppleCrazy
你可以尝试在for循环之外移动迭代器,当'somethingMatches'时,将它设置为'someObjects.length',以便它移出循环..(只是一个念头,从未这样做过) – gkb
@AppleCrazy Exactly ,但正如我所提到的那样会增加for循环中的嵌套。我知道我可以做到这一点,但我想问问是否有办法避免嵌套。 – bash0ne