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
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.
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.
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.
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.
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.
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;
}
});
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