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' ]; 
var i;
for (i = 0; i < array.length; ++i) {
// do something with 'array[i]'

}
Second syntax:

for (var x in array) {
// do something with 'array[x]'

}
< 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.

jQuery.each(array, function(index, value) {
// do something with 'value' (or 'this' which is 'value' )
alert(index+": "+ value);
});
This will produce the following message:

0: one
1: two
2: three
3: four
4: five
If an Object type is passed into the function, The return is the key-value conbinization each time:

var obj = {
"1": "one",
"2": "two"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
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.
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 ) {
alert( i+": " + val );

// Will stop after displaying "three"
return ( val !== "three" );
});
Run in the console shows this:

0: one
1: two
2: three
Resources:
JavaScript For Loop
jQuery API documentation:   jQuery.each()
How to loop through array in jQuery?