变相跳出forEach循环

韩小韩
2023-08-11 / 0 评论 / 8,216 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年08月11日,已超过262天没有更新,若内容或图片失效,请留言反馈。

forEach抛出异常跳出循环

const list = [1, 2, 3, 4, 5, "a", "b", "c", "d", "e"];
try {
    list.forEach((itm) => {
        if (itm === "c") {
            throw new Error("exit");
        }
        console.log(itm);
    });
} catch (e) {
    // console.log(e);
}

变相跳出forEach循环

splice变相跳出循环

const list = [1, 2, 3, 4, 5, "a", "b", "c", "d", "e"];
Object.assign(list).forEach((itm, idx, arr) => {
    if (itm == "c") {
        arr.splice(idx, arr.length - idx);
    }
    console.log(itm);
});

变相跳出forEach循环

2

评论 (0)

取消