7/1/2015 - 4:29 PM

jQuery looping $.each and $().each

jQuery looping $.each and $().each

------------------------------------ For loop (JavaScript)  -----------------------------------------

for (var i = 0; i < substr.length; i++) {
    // do something with `substr[i]`

Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of 'this' within the body of the loop, no unnecessary overhead of function calls.

---------------------------------------- .each() -------------------------------------------------

Iterate over a jQuery object, executing a function for each matched element.

Suppose you have a simple unordered list on the page:
You can select the list items and iterate across them:
$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
A message is thus logged for each item in the list:
0: foo 
1: bar
You can stop the loop from within the callback function by returning false

Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known as implicit iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each() method:
 // The .each() method is unnecessary here:
$( "li" ).each(function() {
  $( this ).addClass( "foo" );
 // Instead, you should rely on implicit iteration:
$( "li" ).addClass( "bar" );

'this' current DOM element being iterated.
To access a jQuery object instead of the regular DOM element, use $( this )

-------------------------------------------  $.each()  -------------------------------------------

The $.each() function is not the same as $(selector).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 value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

$.each([ 52, 97 ], function( index, value ) {
  alert( index + ": " + value );

Note: The $.each() function internally retrieves and uses the length property of the passed collection. So, if the collection has a property called length — e.g. {bar: 'foo', length: 10} — the function might not work as expected.

If an object is used as the collection, the callback is passed a key-value pair each time:
var obj = {
  "flammable": "inflammable",
  "duh": "no duh"
$.each( obj, function( key, value ) {
  alert( key + ": " + value );

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.