欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JavaScript使用类似break机制中断forEach循环的方法

时间:2021-02-23 15:13:31|栏目:JavaScript代码|点击:

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 StopIteration as part of the global scope if it
// isn't already defined.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
// 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 StopIteration. 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 !== StopIteration) {
throw e;
}
}
};
}
})();

使用

// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
if(val == 2)
throw StopIteration;
alert(val);
});

总结

上一篇:wx-charts 微信小程序图表插件的具体使用

栏    目:JavaScript代码

下一篇:深入理解JavaScript 中的执行上下文和执行栈

本文标题:JavaScript使用类似break机制中断forEach循环的方法

本文地址:http://www.codeinn.net/misctech/68165.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有