终止 Array.prototype.forEach 方法运行的方式
通常情况下,Array.prototype 上的遍历方法 forEach、map、filter、... 被调用以后会完整的遍历每一个数组项,并执行内部代码指令,无法被中途终止。
但是可以通过 throw 语句抛出错误,配合 try catch 语句来终止 forEach 语句的执行,如下例所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 */ |
可以进行简单的代码封装,以便于按以上方式进行使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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) } } |
----------- 赠人玫瑰,手有余香 如果本文对您有所帮助,动动手指扫一扫哟 么么哒 -----------
分类:
javascript
标签:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!