jQuery.each method is basically used to loop through every element of both objects and arrays.It is very useful for iterating the elements.
The $.each() method is important because it can be used to iterate over any collection. The syntax for it is as follows:-
jQuery.each( array/object, callback )
For an array the callback is passed like an index of an array and its corresponding array value. With an object,the callback is passed as a key,value pair.
Here is an example below to show the use of $.each() method :-
var arrColors = [ "yellow", "blue", "white", "red", "black" ,"green" ];
jQuery.each(arrColors, function(index, value) {
console.log(this);
return (this != "red"); // will stop running after "red"
});
The obove code snippet will give output : yellow blue white.
var objColors = {
"Red": "Color of rose",
"Yellow": "Color of marigold"
};
$.each( objColors, function( key, value ) {
alert( key + ": " + value );
});
The above code snippet will give the following output :-
Red : Color of rose
Yellow : Color of marigold
0 Comment(s)