forEach(): 没有返回值,实质上等同于 for 循环,对每一项执行 function 函数。即map是返回一个新数组,原数组不变,forEach 是扭转原数组。
不反对 continue,用 return false 或 return true 代替。
不反对 break,用 try catch/every/some 代替:
实现 break:
try { var array = ["first","second","third","fourth"]; // 执行到第3次,完结循环 array.forEach(function(item,index){ if (item == "third") { throw new Error("EndIterative"); } alert(item);// first,sencond }); } catch(e) { if(e.message!="EndIterative") throw e; };
实现 continue:
var arr = [1,2,3,4,5]; var num = 3; arr.some(function(v){ if(v == num) { return; // } console.log(v); });
实现 break:
var arr = [1,2,3,4,5]; var num = 3; arr.every(function(v){ if(v == num) { return false; }else{ console.log(v); return true; } });