博客 / 詳情

返回

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);
    }

image.png

forEach 中包含 try catch 是無法成功的

// 失敗案例   
    [1,2,3,4,5,6].forEach(function(item, index){
        if(item === 3){
            try {
                throw new Error('停止失敗了');
            } catch (error) {
                console.log('error', 'error_停止失敗了');
            }
        }
    });
user avatar 1023 頭像 lanlanjintianhenhappy 頭像 sunhengzhe 頭像 uncletong_doge 頭像
4 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.