[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中查看

希望这对某人有所帮助。

其他回答

如前所述,不能破坏.forEach()。

这里有一种使用ES6迭代器进行foreach的稍微更现代的方法。允许您在迭代时直接访问索引/值。

const array = ['one', 'two', 'three'];

for (const [index, val] of array.entries()) {
  console.log('item:', { index, val });
  if (index === 1) {
    console.log('break!');
    break;
  }
}

输出:

item: { index: 0, val: 'one' }
item: { index: 1, val: 'two' }
break!

链接

Array.prototype.entries()迭代器和发电机解构赋值

我提出的另一个概念是:

函数forEach(数组,cb){var shouldBreak;函数_break(){shouldBreak=true;}for(var i=0,bound=array.length;i<bound;++i){if(shouldBreak){break;}cb(array[i],i,array,_break);}}//用途forEach([‘a’,‘b’,‘c’,‘d’,‘e’,‘f’],函数(char,i,array,_break){console.log(i,char);如果(i===2){_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" }

这只是我想出的解决问题的方法。。。我很确定它解决了最初提问者的问题:

Array.prototype.each = function(callback){
    if(!callback) return false;
    for(var i=0; i<this.length; i++){
        if(callback(this[i], i) == false) break;
    }
};

然后您可以使用以下方法调用它:

var myarray = [1,2,3];
myarray.each(function(item, index){
    // do something with the item
    // if(item != somecondition) return false; 
});

在回调函数中返回false将导致中断。如果这不管用,请告诉我。

我使用return false,这对我有用。