I’m sure some interviewers will ask if MAP can stop the loop? I don’t think it’s a serious question to ask whether the map itself can terminate the loop. This in itself refers to breaking out of the loop with the conditional return or break.
Of course, this question tests your understanding of Map and foeEach.
Maps and forEach can actually break out of the loop, but not by themselves. Instead, they can terminate the loop by throwing a new throw error() and catching the error with a try catch. Ex. :
Let the list = [6]; try{ list.map(item=>{ if(item===3){ throw new Error() } console.log(item) }) } catch {} // 1 2Copy the code
It just prints: 1, 2
But this is done with a try catch plus throw new Error()
But why can’t map and forEach themselves return false or break with an MDN imageAddress of picture:Developer.mozilla.org/zh-CN/docs/…
If the callback is not a function, an error will be returned.
ThisArg = thisArg; thisArg = thisArg; thisArg = thisArg;
Let a = [6] arjun (ap () = > {}) / / this () = > {} is a function (arrow)Copy the code
Because this parameter must be a function, no errors are caught internally, and even if a callback returns false or break, the map does not catch it, so it breaks out of one loop and continues to the next instead of terminating.