forEach can be used for loop traversal like for, but forEach is a higher-order function, for loop is grammar, forEach cannot use break to terminate the loop, use try...catch to catch and throw an exception
var array = ["吃饭", "睡觉", "打豆豆", "写代码"];
try {
// 执行到第3次,结束循环
array.forEach((item, index)=> {
// debugger
if (item == "打豆豆") {
throw new Error("打毛线");
}
console.log(item);// 吃饭 睡觉
});
} catch (e) {
//e.message 上面抛出的异常
console.error(e);
};
// 下面的代码不影响继续执行
console.log("继续执行");