1.因为 forEach() 无法通过正常流程终止,所以可以通过抛出异常的方式实现终止。
try{
var array = ["first","second","third","fourth"];
// 执行到第3次,结束循环
array.forEach(function(item,index) {
if(item == "third"){
throw new Error("EndIterative");
}
console.log(item); // first second
});
}catch(e){
if(e.message != "EndIterative") throw e;
}
// 下面的代码不影响继续执行
console.log("继续执行。。。");
.
本文介绍了一种在JavaScript中利用抛出异常来提前终止数组forEach循环的方法。通过示例代码展示了如何在遍历到特定元素时结束循环,避免了常规终止方式的限制。
911

被折叠的 条评论
为什么被折叠?



