可以利用 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('233'); } catch (error) { console.log('error', error); } } });
基本翻譯
n. 為每一個