我的问题是:如何通过调用的函数触发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;
。
但是这 - 即使它只是一行 - 会增加嵌套。你看到任何可能的解决方案吗?
答案 0 :(得分:0)
如果您使用我推荐的Underscore library,您可以写下以下内容:
_.any(someObjects, doSomething);
function doSomething(object) {
//some code here
return somethingIsDefined &&
doSomethingElse(object);
}
function doSomethingElse(anotherObject) {
//some more code here
return somethingMatches;
}