The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.
The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
(Update: My other answer here lays out the non-jQuery options much more thoroughly. The third option below, jQuery.each
, isn't in it though.)
Four options:
var i;
for (i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
or in ES2015+:
for (let i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of this
within the body of the loop, no unnecessary overhead of function calls (e.g., in theory faster, though in fact you'd have to have so many elements that the odds are you'd have other problems; details).
forEach
:As of ECMAScript5, arrays have a forEach
function on them which makes it easy to loop through the array:
substr.forEach(function(item) {
// do something with `item`
});
Link to docs
(Note: There are lots of other functions, not just forEach
; see the answer referenced above for details.)
Advantages: Declarative, can use a prebuilt function for the iterator if you have one handy, if your loop body is complex the scoping of a function call is sometimes useful, no need for an i
variable in your containing scope.
Disadvantages: If you're using this
in the containing code and you want to use this
within your forEach
callback, you have to either A) Stick it in a variable so you can use it within the function, B) Pass it as a second argument to forEach
so forEach
sets it as this
during the callback, or C) Use an ES2015+ arrow function, which closes over this
. If you don't do one of those things, in the callback this
will be undefined
(in strict mode) or the global object (window
) in loose mode. There used to be a second disadvantage that forEach
wasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEach
is IE8 (and it can't be properly polyfilled there, either).
for-of
:for (const s of substr) { // Or `let` if you want to modify it in the loop body
// do something with `s`
}
See the answer linked at the top of this answer for details on how that works.
Advantages: Simple, straightforward, offers a contained-scope variable (or constant, in the above) for the entry from the array.
Disadvantages: Not supported in any version of IE.
jQuery.each(substr, function(index, item) {
// do something with `item` (or `this` is also `item` if you like)
});
(Link to docs)
Advantages: All of the same advantages as forEach
, plus you know it's there since you're using jQuery.
Disadvantages: If you're using this
in the containing code, you have to stick it in a variable so you can use it within the function, since this
means something else within the function.
You can avoid the this
thing though, by either using $.proxy
:
jQuery.each(substr, $.proxy(function(index, item) {
// do something with `item` (`this` is the same as it was outside)
}, this));
...or Function#bind
:
jQuery.each(substr, function(index, item) {
// do something with `item` (`this` is the same as it was outside)
}.bind(this));
...or in ES2015 ("ES6"), an arrow function:
jQuery.each(substr, (index, item) => {
// do something with `item` (`this` is the same as it was outside)
});
Don't use for..in
for this (or if you do, do it with proper safeguards). You'll see people saying to (in fact, briefly there was an answer here saying that), but for..in
does not do what many people think it does (it does something even more useful!). Specifically, for..in
loops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. But it's not a safe assumption that you can just use it for that. Here's an exploration: http://jsbin.com/exohi/3
I should soften the "don't" above. If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length
is 150,001), and if you use appropriate safeguards like hasOwnProperty
and checking the property name is really numeric (see link above), for..in
can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.
jQuery.each()
jQuery.each(array, callback)
array iteration
jQuery.each(array, function(Integer index, Object value){});
object iteration
jQuery.each(object, function(string propertyName, object propertyValue){});
example:
var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) {
console.log(index, val)
});
var myObj = { firstName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
console.log(propName, propVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
for loop
for (initialExpression; condition; incrementExpression)
statement
example
var substr = [1, 2, 3, 4];
//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
console.log("loop", substr[i])
}
//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
console.log("reverse", substr[i])
}
//step loop
for(var i = 0; i < substr.length; i+=2) {
console.log("step", substr[i])
}
for in
//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
console.log(substr[i]) //note i returns index
}
for of
for(var i of subs) {
//can use break;
console.log(i); //note i returns value
}
forEach
substr.forEach(function(v, i, a){
//cannot use break;
console.log(v, i, a);
})
MDN loops and iterators
No need for jquery here, just a for
loop works:
var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
alert(substr[i]);
}
for
-loopA traditional for
-loop has three components :
These three components are seperated from each other by a ;
symbol. Content for each of these three components is optional, which means that the following is the most minimal for
-loop possible :
for (;;) {
// Do stuff
}
Of course, you will need to include an if(condition === true) { break; }
or an if(condition === true) { return; }
somewhere inside that for
-loop to get it to stop running.
Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index :
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
for
-loop to loop through an arrayThe traditional way to loop through an array, is this :
for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}
Or, if you prefer to loop backwards, you do this :
for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}
There are, however, many variations possible, like eg. this one :
for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
console.log(value);
}
... or this one ...
var i = 0, length = myArray.length;
for (; i < length;) {
console.log(myArray[i]);
i++;
}
... or this one :
var key = 0, value;
for (; value = myArray[key++];){
console.log(value);
}
Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.
Note :Each of these variations is supported by all browsers, including véry old ones!
while
-loopOne alternative to a for
-loop is a while
-loop. To loop through an array, you could do this :
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
Note :
Like traditional for
-loops, while
-loops are supported by even the oldest of browsers.
Also, every while loop can be rewritten as a for
-loop. For example, the while
-loop hereabove behaves the exact same way as this for
-loop :
for(var key = 0;value = myArray[key++];){
console.log(value);
}
for...in
and for...of
In JavaScript, you can also do this :
for (i in myArray) {
console.log(myArray[i]);
}
This should be used with care, however, as it doesn't behave the same as a traditonal for
-loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.
As an alternative to for...in
, there's now also for for...of
. The following example shows the difference between a for...of
loop and a for...in
loop :
var myArray = [3, 5, 7];
myArray.foo = "hello";
for (var i in myArray) {
console.log(i); // logs 0, 1, 2, "foo"
}
for (var i of myArray) {
console.log(i); // logs 3, 5, 7
}
Note :
You also need to consider that no version of Internet Explorer supports for...of
(Edge 12+ does) and that for...in
requires at least IE10.
Array.prototype.forEach()
An alternative to For
-loops is Array.prototype.forEach()
, which uses the following syntax :
myArray.forEach(function(value, key, myArray) {
console.log(value);
});
Note :
Array.prototype.forEach()
is supported by all modern browsers, as well as IE9+.
jQuery.each()
Additionally to the four other options mentioned, jQuery also had its own foreach
variation.
It uses the following syntax :
$.each(myArray, function(key, value) {
console.log(value);
});
Use the each()
function of jQuery.
Here is an example:
$.each(currnt_image_list.split(','), function(index, value) {
alert(index + ': ' + value);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With