Syntax:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
collection - is the array or the object
callback(indexInArray, valueOfElement) - The function that will be executed on every object / array
Example: Array
We’re going to iterate and get the key and value of the given array below:
var arr1 = [ "earth", "mars", "jupiter", "saturn", "venus" ];We can alert each array value by doing:
jQuery.each(arr, function(i, val) { alert(‘key:’+i+ ‘ value: ’+val); });Or you can append it in your HTML DOM using the append function.
jQuery.each(arr, function(i, val) { $("#DOMIDSAMPLE").append(i + " : " + val + "<br/>"); });Going for object is still the same concept.
Example: Object
var objs = { firstname: "John", lastname: "Doe" }; $.each(objs, function(k, v){ alert( "Key: " + k + ", Value: " + v ); });Important: Please take note that $(‘selector’).each() function is different to the above function. $(‘selector’).each() is use for DOM iteration.
0 comments:
Post a Comment