Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery each leave early

Tags:

jquery

each

I have a jQuery for-each loop on an array and wonder if it is possible to leave the loop early.

$(lines).each(function(i){  
    // some code  
    if(condition){  
        // I need something like break;  
    }  
});

break; actually doesn't work, for a reason.

If I'd write a for-loop it would look like that (but I don't want that):

for(i=0; i < lines.length; i++){  
    // some code  
    if(condition){  
        break; // leave the loop 
    }  
};

Thanks in advance -Martin

like image 903
RamboNo5 Avatar asked Dec 07 '09 00:12

RamboNo5


People also ask

How break out of jQuery each?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal 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.

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can we use continue in .each loop?

The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.


2 Answers

According to the docs:

If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Returning non-false is the same as a continue statement in a for loop, it will skip immediately to the next iteration.

like image 111
Vincent Ramdhanie Avatar answered Sep 28 '22 08:09

Vincent Ramdhanie


Return boolean false;
(SEE http://docs.jquery.com/Utilities/jQuery.each , fourth paragraph)

$(lines).each(function(i){  
    // some code  
    if(condition){  
        // I need something like break;  
        return false;
    }  
});
like image 40
micahwittman Avatar answered Sep 28 '22 08:09

micahwittman