Example:
var t = $.each(templos_cache, function(f,g){
$.each(g.requer, function(h,j){
if (parseFloat(g.id) == id){
alert(j.nome); // OK, return 'afrodite'.
return j.nome; // wrong, return [Object object].
}
});
return '';
});
Looking at the code we can see the problem... i can do a set in a variable out of scope but i think that can exist some more elegant way to do this.
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.
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 $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").
Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.
To break out of $.each()
, simply return false;
from the callback function. As quoted from the jQuery documentation:
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.
Edit:
Upon realising you may want to return a value, you could simply pass an object to the callback function as this is passed by reference. See How to append a string value during assignment in Javascript? - this isn't at all any more elegant though, so I'd stick with just setting a variable outside of $.each
as colinmarc said.
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