当前位置:网站首页>JS method to stop foreach

JS method to stop foreach

2022-07-06 21:36:00 Tianmiao studio

You can use try catch Throw an exception to skillfully stop forEach Traverse

Of course not in development During the interview Speak out At least it's also an extra item

//  Right case   Must use  try catch  It's all wrapped up forEach  To stop 
try {
        [1,2,3,4,5,6].forEach(function(item, index){
            console.log(item);
            if(item === 3){
                throw new Error(' prevent ');
            }
        });
    } catch (error) {
        console.log('error_ Block successful ', error);
    }

image.png

forEach Contained in the try catch Can't succeed

//  Failure cases    
    [1,2,3,4,5,6].forEach(function(item, index){
        if(item === 3){
            try {
                throw new Error(' Stop failed ');
            } catch (error) {
                console.log('error', 'error_ Stop failed ');
            }
        }
    });
原网站

版权声明
本文为[Tianmiao studio]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131118365640.html