打破数组循环函数(map、forEach 等)的循环

big*_*ose 2 javascript control-structure

如何break从数组上的隐式循环中中断(类似于语句)?

Array.prototype.map、等函数Array.prototype.forEach意味着对数组元素进行循环。我想有条件地尽早打破这个循环。

这个人为的例子:

const colours = ["red", "orange", "yellow", "green", "blue", "violet"];

colours.map(item => {
    if (item.startsWith("y")) {
        console.log("The yessiest colour!");
        break;
    }
});
Run Code Online (Sandbox Code Playgroud)

导致SyntaxError: unlabeled break must be inside loop or switch.

如何像break语句一样打破循环?

Fin*_*sse 5

您无法使用常规方法来做到这一点。break您可以通过记住循环是否“损坏”来模拟该行为。该解决方案的不足之处在于循环实际上仍在继续(尽管跳过了迭代逻辑)。

let isBroken = false;

colours.map(item => {
    if (isBroken) {
        return;
    }
    if (item.startsWith("y")) {
        console.log("The yessiest colour!");
        isBroken = true;
        return;
    }
});
Run Code Online (Sandbox Code Playgroud)

对于您的示例,最佳解决方案是使用普通for循环。

for (colour of colours) {
    if (colour.startsWith("y")) {
        console.log("The yessiest colour!");
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用一种肮脏的方式来实际停止map循环。

colours.map((item, index, array) => {
    if (item.startsWith("y")) {
        console.log("The yessiest colour!");
        array.splice(0, index);
    }
});
// The colours array will be modified after this loop
Run Code Online (Sandbox Code Playgroud)