跳出forEach循环

184 阅读1分钟

错误用法1: 原生态的forEach()方法体中,结束循环不能使用break。

let array = ["first","second","third","fourth",,"five"];array.forEach(function(item,index){    if (item == "third") {        break;    }    console.log(item)});

报错:


错误用法2: return false; 会遍历数组所有元素,只是执行到第3次时,return false下面的代码不再执行而已

let array = ["first","second","third","fourth",,"five"];array.forEach(function(item,index){    if (item == "third") {       return false;    }    console.log(item)});

正确用法1: 使用try cach 因为forEach()无法通过正常流程终止,所以可以通过抛出异常的方式实现终止;

try {    var array = ["first","second","third","fourth","five"];        // 执行到第3次,结束循环    array.forEach(function(item,index){        if (item == "third") {            throw new Error("EndIterative");        }        console.log(item);// first,sencond    });} catch(e) {    if(e.message!="EndIterative") throw e;};// 下面的代码不影响继续执行console.log(10);


正确用法2: forEach函数不支持break,可以用every函数替代

let array = ["first","second","third","fourth","five"];array.every(function (item, i) {    if (item === "third") {      return false    }	console.log(item)    return true })

相关资料:www.cnblogs.com/Marydon2017…