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

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


当前回答

没有内置的功能可以为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});

其他回答

使用array.prototype.every函数,它为您提供了中断循环的实用程序。请参阅Mozilla开发者网络上的Javascript文档示例

在其他网站上找到此解决方案。您可以在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/

如前所述,不能破坏.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的变体,该变体允许break、continue、return甚至async/await:(用TypeScript编写的示例)

export type LoopControlOp = "break" | "continue" | ["return", any];
export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp;

Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) {
    for (let i = 0; i < this.length; i++) {
        const controlOp = func(this[i], i, this);
        if (controlOp == "break") break;
        if (controlOp == "continue") continue;
        if (controlOp instanceof Array) return controlOp[1];
    }
};

// this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry
Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) {
    for (let i = 0; i < this.length; i++) {
        const controlOp = await func(this[i], i, this);
        if (controlOp == "break") break;
        if (controlOp == "continue") continue;
        if (controlOp instanceof Array) return controlOp[1];
    }
};

用法:

function GetCoffee() {
    const cancelReason = peopleOnStreet.ForEach((person, index)=> {
        if (index == 0) return "continue";
        if (person.type == "friend") return "break";
        if (person.type == "boss") return ["return", "nevermind"];
    });
    if (cancelReason) console.log("Coffee canceled because: " + cancelReason);
}

这不是最有效的,因为你仍然循环所有元素,但我认为这可能值得考虑非常简单的:

let keepGoing = true;
things.forEach( (thing) => {
  if (noMore) keepGoing = false;
  if (keepGoing) {
     // do things with thing
  }
});