在函数调用中中断或继续循环

时间:2016-11-17 06:12:26

标签: javascript performance code-complexity

我的问题是:如何通过调用的函数触发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;
但是这 - 即使它只是一行 - 会增加嵌套。你看到任何可能的解决方案吗?

1 个答案:

答案 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;
}