Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break/continue across nested for each loops in TypeScript

Tags:

typescript

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       }          }          } 
like image 860
gihan-maduranga Avatar asked Feb 15 '18 07:02

gihan-maduranga


People also ask

How do you break a forEach loop in TypeScript?

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!

Can you break out of a for each loop?

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.

How do you stop a loop when a condition is met TypeScript?

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.


2 Answers

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;     }   } 
like image 128
Mahmood Dehghan Avatar answered Sep 19 '22 11:09

Mahmood Dehghan


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; //           }      }    } 
like image 38
lazydeveloper Avatar answered Sep 21 '22 11:09

lazydeveloper