I have the following code:
foreach(// Some condition here) { while (// Some condition here) { foreach (// Some condition here) { if (// Condition again) { //Do some code } if (// Condition again) { //Stop the first foreach then go back to first foreach } } } }
What I want to do is when I hit the 2nd if
statement on the last foreach
loop is to return on the first foreach
loop.
Note: If the 2nd if
statement is not true, it should continue the last foreach
loop until the condition is not true.
Thanks in advance!
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
The reason why using a return statement to continue in a JavaScript forEach loop works is because when you use a forEach loop you have to pass in a callback function. The only way to continue to the next iteration is when your callback function completes and finishes running the code within itself.
The only way to this directly is with a goto
.
Another (better) option is to restructure until the problem goes away. For instance by putting the inner code (while + foreach) in a method and use return to get back.
Something like this:
resetLoop = false; for(// Some condition here) { while (// Some condition here) { foreach (// Some condition here) { if (// Condition again) { //Do some code } if (// Condition again) { //Stop the first foreach then go back to first foreach resetLoop = true; break; } } if (resetLoop) break; } if (resetLoop) { // Reset for loop to beginning // For example i = 0; } }
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