-
How does forEach break out of the loop? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
forEach cannot jump out of the loop through break or return, why? Students who have implemented forEach should know that the callback function of forEach forms a scope. Using return in it will not jump out, but will only be regarded as continue
|
Beta Was this translation helpful? Give feedback.
forEach cannot jump out of the loop through break or return, why? Students who have implemented forEach should know that the callback function of forEach forms a scope. Using return in it will not jump out, but will only be regarded as continue
So how do you get out of the loop? You can use try catch
function getItemById(arr, id) { var item = null; try { arr.forEach(function (curItem, i) { if (curItem.id == id) { item = curItem; throw Error(); } }) } catch (e) { } return item; }