Skip to content
Discussion options

You must be logged in to vote

How does forEach break out of the loop?

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; }

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by xiao-ice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants