【问题标题】:Breaking out of a while loop from within an inner function's body从内部函数体内跳出while循环
【发布时间】:2013-12-12 21:03:31
【问题描述】:

如果我有:

while(foo) {
  var x = bar.filter(function(){ /* any problems with using `break;` here to exit the while-loop? */ });
  bar(), baz();
  // and so on...
}

会有什么奇怪或意外的行为吗?

【问题讨论】:

  • 解释原任务
  • break; 在函数内调用时将不起作用,所以问题很多
  • @zerkms 什么不清楚?
  • @musefan 你知道的任何解决方法?
  • 你不能从嵌入函数中。

标签: javascript while-loop break


【解决方案1】:

break 打破了它直接出现在其中的循环;如果您在函数(您的 filter 迭代器)中的循环(或开关)之外有 break,这是语法错误。

给函数设置的while添加条件:

var stop = false;
while(foo && !stop) {
  var x = bar.filter(function(){
    if (someCondition) {
        stop = true;
    }
  });
  bar(), baz();
}

当然也可以直接设置foo

while(foo) {
  var x = bar.filter(function(){
    if (someCondition) {
        foo = false;
    }
  });
  bar(), baz();
}

...但我不知道foo 是什么以及这是否合理。

如果你需要barbaz 在中断条件下不被执行,你需要添加一个守卫:

var stop = false;
while(foo && !stop) {
  var x = bar.filter(function(){
    if (someCondition) {
        stop = true;
    }
  });
  if (!stop) {
      bar(), baz();
  }
}

while(foo) {
  var x = bar.filter(function(){
    if (someCondition) {
        foo = false;
    }
  });
  if (foo) {
      bar(), baz();
  }
}

【讨论】:

    【解决方案2】:

    您不能在 while 循环内的闭包函数中使用 break,但是,您可以例如使用false 作为显式返回值来发出循环中断:

    var count = 0,
        foo = true;
    while(foo) {
      var bar = function() {
        if (++count < 23) { 
          console.log(count);
          return true; 
        } else { 
          return false; 
        }
      };
    
      if (bar() === false) { break; }
    }
    

    对于您的具体示例,由于filter 不返回闭包函数的返回值,因此您必须通过设置您在while 循环之外定义的值来中断循环,例如foo 为假:

    var count = 0,
        baz = [1,2,3],
        foo = true;
    while(foo) {
      var x = baz.filter(function(a) { 
        if (a > 2) {
          foo = false;
        }
        return a < 3  
      });
    }
    

    【讨论】:

    • -1:你为什么要自己决定 OP 不再需要 filter 函数?
    • 哦,我明白了。我更喜欢使用警卫 - 让它更简单。
    【解决方案3】:

    如前所述,您不能在函数体内使用break

    但根据您要完成的具体内容,您也可以切换逻辑,直到中断才重复,但在需要时从函数内触发下一次迭代:

    function filterFunc() {
        if (condition) {
            iter();
        }
    }
    
    function iter() {
        var x = bar.filter(filterFunc);
        bar(), baz();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 2020-06-16
      • 2010-11-28
      • 1970-01-01
      • 2012-01-16
      相关资源
      最近更新 更多