假設當咱們只需知道某個數組有沒有某個屬性,若是找到了直接跳出循環,省略掉剩下的循環步驟是較優化的操做,可是for中是能夠利用break跳出循環,但break在forEach中無效,那麼forEach能不能跳出循環呢?固然是能夠。數組
1.正常for循環break跳出循環oop
let strArr = ['a', 'b', 'c', 'd'], i = 0, length = strArr.length; for (; i < length; i++) { console.log(strArr[i]);//a if(arr[i] === 'a'){ //do something }; break; };
2.forEach結合try...catch()能夠跳出循環優化
try { var arr = [1, 2, 3, 4]; arr.forEach(function (item, index) { //跳出條件 if (item === 3) { throw new Error("LoopTerminates"); } //do something console.log(item); }); } catch (e) { if (e.message !== "LoopTerminates") throw e; };