Browse an array with jQuery.each()
The examples below show how to browse and read the elements of a JavaScript array using the for loop and the jQuery.each().JavaScript for loop
The for loop is easy to understand and depends on jQuery since it is written in JavaScript.var array = [ 'un', 'two', 'three', 'four', 'five' ];Second syntax:
var i;
for (i = 0; i < array.length; ++i) {
// do something with 'array[i]'
}
for (var x in array) {< h2>The jQuery.each()jQuery.each() function is an iterative function, it can be used to traverse objects and arrays that are iterated by a numeric index, from 0 to size-1. The other objects are iterated through their properties.
// do something with 'array[x]'
}
jQuery.each(array, function(index, value) {This will produce the following message:
// do something with 'value' (or 'this' which is 'value' )
alert(index+": "+ value);
});
0: oneIf an Object type is passed into the function, The return is the key-value conbinization each time:
1: two
2: three
3: four
4: five
var obj = {Advantage: The jquery.each() function can contain a declaration of a function inside it and increments the position automatically in the "index" variable. The value is stored in the "item" variable that can be accessed directly.
"1": "one",
"2": "two"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
Disadvantage: if you use the keyword this inside the code, you need to associate it with a variable so that you can use it without the function, since this means something else within the function.
You can force the exit of the $.each() loop in a particular iteration by putting the return of the function back false. Returning true is equivalent to the continuous statement in a for loop, it will move on to the next iteration.
jQuery.each( array, function( i, val ) {Run in the console shows this:
alert( i+": " + val );
// Will stop after displaying "three"
return ( val !== "three" );
});
0: oneResources:
1: two
2: three
JavaScript For Loop
jQuery API documentation: jQuery.each()
How to loop through array in jQuery?