js让forEach停止的方法

2022-02-13  本文已影响0人  天渺工作室

可以利用 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);
            }
        }
    });
上一篇 下一篇

猜你喜欢

热点阅读