RsD0p9BK
12/10/2015 - 4:04 AM

each.js

// Iterating over jQuery and non-jQuery Objects

var arr = [ 1, 2, 3, 4, 5 ];
var sum = 0;
var obj = {
  foo: 1,
  bar: 2
}

// 0 - loop array
for ( var i = 0, l = arr.length; i < l; i++ ) {
  sum += arr[ i ];
}

// 1 - loop array
$.each( arr, function( index, value ){
  sum += value;
});


// 2 - loop through object value
for (var item in obj) {
  sum += obj[ item ];
}

// 3 - loop object with key/value
$.each( obj, function( key, value ) {
  sum += value;
});

// 4 - loop through jQuery collections
$( "li" ).each( function( index, element ) {
    console.log( $( this ).text() );
});

// https://learn.jquery.com/using-jquery-core/iterating/