学无先后,达者为师

网站首页 前端文档 正文

js让forEach停止的方法

作者:天渺工作室 更新时间: 2022-02-27 前端文档

可以利用 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);
            }
        }
    });

原文链接:https://blog.csdn.net/sinat_37255207/article/details/122907842

栏目分类
最近更新