[1,2,3].forEach(function(el) {
    if(el === 1) break;
});

如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。


当前回答

这是一个for循环,但像forEach()一样在循环中维护对象引用,但可以中断。

var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
    if(el === 1) break;
}

其他回答

你可以按照下面的代码操作,这对我很有用:

 var     loopStop = false;
YOUR_ARRAY.forEach(function loop(){
    if(loopStop){ return; }
    if(condition){ loopStop = true; }
});

为什么不尝试将函数包装在Promise中?

我提出这个问题的唯一原因是我在API中使用了一个函数,该函数的作用方式与forEach类似。我不希望它在找到值后继续迭代,我需要返回一些东西,所以我只需要解析Promise并以这种方式执行。

traverseTree(doc): Promise<any> {
  return new Promise<any>((resolve, reject) => {
    this.gridOptions.api.forEachNode((node, index) => {
    //the above function is the one I want to short circuit.
      if(node.data.id === doc.id) {
        return resolve(node);
      }
    });
  });
}

那么你所需要做的就是做一些事情,比如

this.traverseTree(doc).then((result) => {
   this.doSomething(result);
});

我上面的例子是在typescript中,只需忽略类型。逻辑应该有助于你“打破”你的循环。

没有内置的功能可以为Each进行破解。要中断执行,必须抛出某种异常。

var BreakException={};尝试{[1,2,3]对于每个(函数(el){控制台日志(el);如果(el==2)抛出BreakException;});}捕获(e){如果(e!==BreakException)抛出e;}

JavaScript异常并不漂亮。如果你真的需要打破传统的for循环,那么它可能更合适。

使用数组#some

而是使用Array#some:

[1,2,3]一些(函数(el){控制台日志(el);返回el==2;});

这之所以有效,是因为只要按数组顺序执行的任何回调返回true,就会立即返回true,从而缩短其余回调的执行。

有些,它的逆every(返回false时停止)和forEach都是ECMAScript第五版方法,需要在缺少它们的浏览器上添加到Array.prototype中。

使用数组#间隔

[1,2,3]每(v=>{如果(v>2){return false//“break”}控制台日志(v);return true//如果不中断,则必须返回true});

如果您想使用Dean Edward的建议并抛出StopIteration错误以跳出循环而不必捕获错误,则可以使用以下函数(最初来自此处):

// Use a closure to prevent the global namespace from be polluted.
(function() {
  // Define StopIteration as part of the global scope if it
  // isn't already defined.
  if(typeof StopIteration == "undefined") {
    StopIteration = new Error("StopIteration");
  }

  // The original version of Array.prototype.forEach.
  var oldForEach = Array.prototype.forEach;

  // If forEach actually exists, define forEach so you can
  // break out of it by throwing StopIteration.  Allow
  // other errors will be thrown as normal.
  if(oldForEach) {
    Array.prototype.forEach = function() {
      try {
        oldForEach.apply(this, [].slice.call(arguments, 0));
      }
      catch(e) {
        if(e !== StopIteration) {
          throw e;
        }
      }
    };
  }
})();

上述代码将使您能够运行以下代码,而无需执行自己的try-catch子句:

// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
  if(val == 2)
    throw StopIteration;
  alert(val);
});

需要记住的一点是,如果Array.prototype.forEach函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。

我为此使用了nullhack,它试图访问null的属性,这是一个错误:

try {
  [1,2,3,4,5]
  .forEach(
    function ( val, idx, arr ) {
      if ( val == 3 ) null.NULLBREAK;
    }
  );
} catch (e) {
  // e <=> TypeError: null has no properties
}
//