大家好,又见面了,我是你们的朋友全栈君。
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。对于空数组不会执行回调函数
回调函数的参数 function(currentValue, index, arr)
currentValue 必需。当前元素
index 可选。当前元素的索引值
arr 可选。当前元素所属的数组对象
之前没有注意 如何 跳出循环,一直做if 判断做出操作,直到有一次有这样的需求 才发现 break 和 return false 无效
let arr =[1,2,3,4,5,6,7,8]
// 直接就报错了 arr.forEach(function(item,index){ if (item === 4) { break; } alert(item); });
let arr =[1,2,3,4,5,6,7,8] arr.forEach(function(item,index){ if (item === 4) { return false } console.log(item); });
期望 会遍历数组所有元素,只是执行到第4次,return false下面的代码不再执行而已
实际上没有达到效果
return fasle 只是中止本次继续执行,而不是终止循环
解决办法 可以通过抛出异常的方式终止循环
try { let arr =[1,2,3,4,5,6,7,8] // 执行到第4次,结束循环 arr.forEach(function(item,index){ if (item === 4) { throw new Error(“EndIterative”); } console.log(item);// 1,2,3 }); } catch(e) { if(e.message!=”EndIterative”) throw e; }; // 下面的代码不影响继续执行 console.log(10);
另外 for 循环 可以 用 break 来终止循环
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135904.html原文链接:https://javaforall.cn