JavaScript使用类似break机制中断forEach循环的方法
JavaScript数组对象,有一个forEach方法,可枚举每一个数组元素,但并不支持类似for循环的break语法,中断循环:
[1,2,3].forEach(function(item){
//if(!item)break;不支持
});
解决办法,可抛出一个特殊异常,来中断forEach循环,原理:
varBreakException={};
try{
[1,2,3].forEach(function(el){
console.log(el);
if(el===2)throwBreakException;
});
}catch(e){
if(e!==BreakException)throwe;
}
也可复写forEach方法:
//Useaclosuretopreventtheglobalnamespacefrombepolluted.
(function(){
//DefineStopIterationaspartoftheglobalscopeifit
//isn'talreadydefined.
if(typeofStopIteration=="undefined"){
StopIteration=newError("StopIteration");
}
//TheoriginalversionofArray.prototype.forEach.
varoldForEach=Array.prototype.forEach;
//IfforEachactuallyexists,defineforEachsoyoucan
//breakoutofitbythrowingStopIteration.Allow
//othererrorswillbethrownasnormal.
if(oldForEach){
Array.prototype.forEach=function(){
try{
oldForEach.apply(this,[].slice.call(arguments,0));
}
catch(e){
if(e!==StopIteration){
throwe;
}
}
};
}
})();
使用
//Showthecontentsuntilyougetto"2".
[0,1,2,3,4].forEach(function(val){
if(val==2)
throwStopIteration;
alert(val);
});
总结
以上所述是小编给大家介绍的JavaScript使用类似break机制中断forEach循环的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!