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

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


当前回答

现在,在ECMAScript2015(也称为ES6)中使用新的for of循环有更好的方法来实现这一点。例如,此代码不打印数字5之后的数组元素:

常量arr=[0,1,2,3,4,5,6,7,8,9,10];for(arr常量){控制台日志(el);如果(el==5){打破}}

从文档中:

两者都用于。。。为。。。of语句对某些内容进行迭代。它们之间的主要区别在于迭代的内容。用于。。。in语句按原始插入顺序迭代对象的可枚举财产。用于。。。of语句迭代可迭代对象定义要迭代的数据。

迭代中需要索引吗?可以使用Array.entries():

for (const [index, el] of arr.entries()) {
  if ( index === 5 ) break;
}

其他回答

如果您想使用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函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。

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

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

我为此使用了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
}
//

从您的代码示例中,它看起来像Array.prototype.find,这就是您要查找的:Array.prototy.find()和Array.prototype.findIndex()

[1, 2, 3].find(function(el) {
    return el === 2;
}); // returns 2

在其他网站上找到此解决方案。您可以在try/catch场景中包装forEach。

if(typeof StopIteration == "undefined") {
 StopIteration = new Error("StopIteration");
}

try {
  [1,2,3].forEach(function(el){
    alert(el);
    if(el === 1) throw StopIteration;
  });
} catch(error) { if(error != StopIteration) throw error; }

此处提供更多详细信息:http://dean.edwards.name/weblog/2006/07/enum/