JavaScript使用类似break机制中断forEach循环的方法
程序员文章站
2022-06-11 22:22:24
javascript数组对象,有一个foreach方法,可枚举每一个数组元素,但并不支持类似for循环的break语法,中断循环:
[1,2,3].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 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); });
总结
以上所述是小编给大家介绍的javascript使用类似break机制中断foreach循环的方法,希望对大家有所帮助
下一篇: js html实现计算器功能