js 让forEach停止遍历的巧妙方法
可以利用 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. 为每一个