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

2024-01-03

我怎样才能打破(类似于break语句)来自数组的隐式循环?

The 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;
    }
});

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

我怎样才能以同样的方式打破循环break声明会吗?


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

let isBroken = false;

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

对于您的示例来说,最好的解决方案是使用普通的for loop.

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

您也可以使用肮脏的方式来实际停止map loop.

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

打破数组循环函数(map、forEach 等)的循环 的相关文章

随机推荐