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. 为每一个
网络释义
foreach: 语句
foreach file: 循环取出记录集内容
FOREACH B: 遍历B

 

posted @ 2022-02-13 01:16  天渺工作室  阅读(798)  评论(0编辑  收藏  举报