Reputation: 12056
I'm getting strange behavior where I want to return immediately in the middle of a jQuery Each Loop, and my expectation is, the function below should return TRUE (the condition matches). But I'm still getting FALSE. This would have worked in Java, but doesn't work in JS/jQuery?
function returnFromLoop(eventIDs) {
jQuery.each(eventIDs, function(index, item) {
if (item.indexOf("TEST") != -1) {
return true;
}
});
return false;
}
var eventIDs = [];
eventIDs.push('abc');
eventIDs.push('defTEST');
eventIDs.push('ghi');
var result = returnFromLoop(eventIDs);
console.log('result = ' + result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Views: 116
Reputation: 15625
The problem is you are trying to return two functions out so I used an extra variable for solution. return true
act as a type of continue so you need to return false.
https://stackoverflow.com/a/8224424/6517383 will help you understand more.
function returnFromLoop(eventIDs) {
var state = 0;
jQuery.each(eventIDs, function(index, item) {
if (item.indexOf("TEST") != -1) {
state = 1;
return 1;
}
});
if(state == 1) {
return true;
}
return false;
}
var eventIDs = [];
eventIDs.push('abc');
eventIDs.push('defTEST');
eventIDs.push('ghi');
var result = returnFromLoop(eventIDs);
console.log('result = ' + result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 14562
A return true
inside jQuery's .each()
method does not break out of the loop. Instead you can use return false
to break out of the loop.
Then, in order to capture the return value, you can use a variable. In the snippet below I have used variable returnValue
. Once out of the loop, you can return that variable.
From http://api.jquery.com/jQuery.each/:
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.
function returnFromLoop(eventIDs) {
var returnValue = false;
jQuery.each(eventIDs, function(index, item) {
if (item.indexOf("TEST") != -1) {
returnValue = true;
return false; // Equivalent to break statement.
}
});
return returnValue;
}
var eventIDs = [];
eventIDs.push('abc');
eventIDs.push('defTEST');
eventIDs.push('ghi');
var result = returnFromLoop(eventIDs);
console.log('result = ' + result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1