Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return from a $.each operation? (jQuery)

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.

like image 515
tiagomac Avatar asked Jul 07 '11 19:07

tiagomac


People also ask

How do I get out of each loop in jQuery?

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.

What is the use of jQuery each () function?

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.

What does $() do in Javascript?

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").

How do you iterate through an array in jQuery?

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.


1 Answers

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.

like image 93
Jack Murdoch Avatar answered Sep 20 '22 18:09

Jack Murdoch