I tried to use break inside nested for each loop and it says jump target cannot cross function boundary. please let me know how can i break nested for each loop when certain condition is met in TypeScript.
groups =[object-A,object-B,object-C] groups.forEach(function (group) { // names also an array group.names.forEach(function (name) { if (name == 'SAM'){ break; //can not use break here it says jump target cannot cross function boundary } } }
To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection. Copied!
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the . forEach() method is the wrong tool, use a plain loop instead.
Using TypeScript break to terminate a loop The break statement allows you to terminate a loop and pass the program control over the next statement after the loop. You can use the break statement inside the for , while , and do... while statement.
forEach
accepts a function and runs it for every element in the array. You can't break the loop. If you want to exit from a single run of the function, you use return
.
If you want to be able to break the loop, you have to use for..of
loop:
for(let name of group.names){ if (name == 'SAM') { break; } }
ForEach doesn't support break, you should use return
groups =[object-A,object-B,object-C] groups.forEach(function (group) { // names also an array group.names.forEach(function (name) { if (name == 'SAM'){ return; // } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With