从内部函数体内突破while循环

use*_*492 3 javascript break while-loop

如果我有:

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

会有任何奇怪或意外的行为吗?

T.J*_*der 6

break打破它直接出现的循环; 如果你break在函数(你的filter迭代器)中有一个循环(或开关)之外,那就是语法错误.

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

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

或者当然,它可以直接设置foo:

while(foo) {
  var x = bar.filter(function(){
    if (someCondition) {
        foo = false;
    }
  });
  bar(), baz();
}
Run Code Online (Sandbox Code Playgroud)

......但我不知道是什么foo,这是否合理.

如果你需要barbaz不是在破坏条件下执行,你需要添加一个警卫:

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

要么

while(foo) {
  var x = bar.filter(function(){
    if (someCondition) {
        foo = false;
    }
  });
  if (foo) {
      bar(), baz();
  }
}
Run Code Online (Sandbox Code Playgroud)


Bea*_*rtz 3

您不能break在 while 循环内的闭包函数中使用,但是,您可以用作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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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  
  });
}
Run Code Online (Sandbox Code Playgroud)