How can I exit from $.each
loop when a condition is met? I don't want to iterate the collection further.
$(vehicles).each(function() {
if (this["@id"] === vehicleId[0]) {
vehicle = this;
}
});
I tried with break;
& return;
statement but it looks the execution doesn't not stop at that point. Any idea would be greatly appreciated.
Tips. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.
Just to provide a quick alternative, you can create a server action, in which you exit your for-each loop early by going to an end node. Then pass the data back to your main flow via the output.
The if statement is not a loop . it is either not exected at all or exectuted just once. So it absolutely makes no sense to put a break inside the body of if.
To break out of a for loop, you can use the endloop, continue, resume, or return statement. endfor; If condition is true, statementlist2 is not executed in that pass through the loop, and the entire loop is closed.
Returning false is the equivalent of breaking out of a $.each loop. So in your example:
if (this["@id"] === vehicleId[0]) { vehicle = this; return false; }
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