Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from $.each function when condition met

Tags:

jquery

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.

like image 653
Senthil Elayappan Avatar asked Jun 29 '10 15:06

Senthil Elayappan


People also ask

How do you exit a loop if condition is met?

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.

How do you exit from for each?

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.

Can we use break in if?

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.

How do you break a loop?

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.


1 Answers

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; }
like image 105
Joey C. Avatar answered Oct 16 '22 12:10

Joey C.