forEach同for一样都可以用于循环遍历,但是forEach是高阶函数,for循环是语法,forEach中无法使用break终止循环,使用try…catch捕获并抛出异常
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("继续执行");