终止 Array.prototype.forEach 方法运行的方式

通常情况下,Array.prototype 上的遍历方法 forEach、map、filter、... 被调用以后会完整的遍历每一个数组项,并执行内部代码指令,无法被中途终止。

但是可以通过 throw 语句抛出错误,配合 try catch 语句来终止 forEach 语句的执行,如下例所示:

var arr = [1,2,3,4,5,6]
try {
    arr.forEach((item, index, a) => {
        if (index >= 2) {
            throw new Error('error')
        } else {
            console.log(item)
        }
    })
} catch (err) {
    console.log(err)
}
console.log('---- end')

/** log
1
2
Error: error
    at <anonymous>:5:19
    at Array.forEach (<anonymous>)
    at <anonymous>:3:9
---- end
*/

 

  可以进行简单的代码封装,以便于按以上方式进行使用:

interface CallBack {
    (item: any, index: number, arr: any[]): void
}
interface Condition {
    (item: any, index: number, arr: any[]): boolean
}
interface Traverse {
    (arr: any[], method: string, callback: CallBack, condition: Condition): void
}
/** */
const traverse:Traverse = (arr, method, callback, condition) => {
    try {
        arr[method]((item: any, index: number, a: any[]) => {
            if (condition(item, index, a)) {
                throw new Error('error')
            } else {
                callback(item, index, a)
            }
        })
    } catch (err) {
        console.log(err)
    }
}

  






----------- 赠人玫瑰,手有余香     如果本文对您有所帮助,动动手指扫一扫哟   么么哒 -----------

 

 
posted @ 2022-09-04 22:17  hello_exec  阅读(120)  评论(0)    收藏  举报