tags:

views:

134

answers:

2

Hi, 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

+2  A: 

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;
    }  
});
micahwittman
life can be so easy sometimes. thanks :)
RamboNo5
You're welcome, Martin.
micahwittman
+4  A: 

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.

Vincent Ramdhanie
Aah thanks. That's good to know!
RamboNo5