How to break/continue across nested for each loops in 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
}
}
}
Solution 1:
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;
}
}
Solution 2:
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; //
}
}
}