1、利用try catch
try {
const arr = [1, 2, 3, 4];
arr.forEach(function (item, index) {
// 跳出条件
if (item === 3) {
throw new Error("verynice");
}
// do something
console.log(item);
});
} catch (e) {
if (e.message !== "verynice") throw e;
};
2、利用其它数组方法折中实现,如find、findIndex、some,下面是find的实现
const arr = [1, 2, 3, 4];
arr.findIndex(function (item, index) {
// do something
console.log(item);
// 退出条件
return item === 3;
});