JavaScript使用类似break机制中断forEach循环的方法
网络编程 2021-07-04 16:47www.168986.cn编程入门
这篇文章主要介绍了JavaScript使用类似break机制中断forEach循环的方法,需要的朋友可以参考下
JavaScript数组对象,有一个forEach方法,可枚举每一个数组元素,但并不支持类似for循环的break语法,中断循环:
[1,2,3].forEach(function(item) { // if(!item) break; 不支持 });
解决办法,可抛出一个特殊异常,来中断forEach循环,原理:
var BreakException = {}; try { [1, 2, 3].forEach(function(el) { console.log(el); if (el === 2) throw BreakException; }); } catch (e) { if (e !== BreakException) throw e; }
也可复写forEach方法:
// Use a closure to prevent the global namespace from be polluted. (function() { // Define SIteration as part of the global scope if it // isn't already defined. if(typeof SIteration == "undefined") { SIteration = new Error("SIteration"); } // The original version of Array.prototype.forEach. var oldForEach = Array.prototype.forEach; // If forEach actually exists, define forEach so you can // break out of it by throwing SIteration. Allow // other errors will be thrown as normal. if(oldForEach) { Array.prototype.forEach = function() { try { oldForEach.apply(this, [].slice.call(arguments, 0)); } catch(e) { if(e !== SIteration) { throw e; } } }; } })();
使用
// Show the contents until you get to "2". [0,1,2,3,4].forEach(function(val) { if(val == 2) throw SIteration; alert(val); });
总结
以上所述是长沙网络推广给大家介绍的JavaScript使用类似break机制中断forEach循环的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!
上一篇:js html实现计算器功能
下一篇:小程序登录态管理的方法示例
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程