Jquery each - Stop loop and return object
Because when you use a return
statement inside an each
loop, a "non-false" value will act as a continue
, whereas false
will act as a break
. You will need to return false
from the each
function. Something like this:
function findXX(word) {
var toReturn;
$.each(someArray, function(i) {
$('body').append('-> '+i+'<br />');
if(someArray[i] == word) {
toReturn = someArray[i];
return false;
}
});
return toReturn;
}
From the docs:
We can break the $.each() loop at a particular iteration by making the callback 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.
modified $.each
function
$.fn.eachReturn = function(arr, callback) {
var result = null;
$.each(arr, function(index, value){
var test = callback(index, value);
if (test) {
result = test;
return false;
}
});
return result ;
}
it will break loop on non-false/non-empty result and return it back, so in your case it would be
return $.eachReturn(someArray, function(i){
...