可以利用 try catch 的拋出異常行為來巧妙的停止forEach遍歷
開發中當然不能這麼寫 面試的時候 可以説出來 起碼也算是也算加分項了
// 正確案例 必須用 try catch 整個包住forEach 才能停止
try {
[1,2,3,4,5,6].forEach(function(item, index){
console.log(item);
if(item === 3){
throw new Error('阻止');
}
});
} catch (error) {
console.log('error_阻止成功', error);
}
forEach 中包含 try catch 是無法成功的
// 失敗案例
[1,2,3,4,5,6].forEach(function(item, index){
if(item === 3){
try {
throw new Error('停止失敗了');
} catch (error) {
console.log('error', 'error_停止失敗了');
}
}
});