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

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


当前回答

如果您需要根据数组中已经存在的元素的值进行中断(例如,如果中断条件不依赖于在为数组分配元素值后可能发生变化的运行时变量),您也可以使用slice()和indexOf()的组合,如下所示。

如果您需要在forEach到达“Apple”时中断,可以使用

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple"));
// fruitsToLoop = Banana,Orange,Lemon

fruitsToLoop.forEach(function(el) {
    // no need to break
});

如W3Schools.com中所述,slice()方法将数组中选定的元素作为新的数组对象返回。原始阵列将不会更改。

在JSFiddle中查看

希望这对某人有所帮助。

其他回答

同意@bobince,支持。

此外,仅供参考:

Prototype.js有这样的功能:

<script type="text/javascript">
  $$('a').each(function(el, idx) {
    if ( /* break condition */ ) throw $break;
    // do something
  });
</script>

$break将由Prototype.js在内部捕获和处理,打破“each”循环,但不会产生外部错误。

有关详细信息,请参见Prototype.JS API。

jQuery也有一种方法,只需在处理程序中返回false,即可尽早中断循环:

<script type="text/javascript">
  jQuery('a').each( function(idx) {
    if ( /* break condition */ ) return false;
    // do something

  });
</script>

有关详细信息,请参见jQuery API。

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

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

尝试“查找”:

var myCategories = [
 {category: "start", name: "Start", color: "#AC193D"},
 {category: "action", name: "Action", color: "#8C0095"},
 {category: "exit", name: "Exit", color: "#008A00"}
];

function findCategory(category) {
  return myCategories.find(function(element) {
    return element.category === category;
  });
}

console.log(findCategory("start"));
// output: { category: "start", name: "Start", color: "#AC193D" }

还有一种方法:

var wageType = types.filter(function(element){
  if(e.params.data.text == element.name){
    return element;
  }
});
console.dir(wageType);

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