MatLabFan
MatLabFan

Reputation:

What is the equivalent of a for-each loop in jQuery?

I recently started working with jQuery and was wondering how I would iterate through a collection (an array or list of items) of items and sum their contents.

Does jQuery have something like a for-loop like many other languages do?

Would there be an easy way to implement this - if this isn't easily do-able?

Upvotes: 3

Views: 7330

Answers (3)

Rion Williams
Rion Williams

Reputation: 76597

What you are looking for is the jQuery each() function - which will allow you to iterate through any given field(s) and perform an action.

Usage:

var array = ["stack", "overflow"];
$.each(array, function() {
      // Perform actions here (this) will be your current item
});

Example (Summing an Array of Integers):

var array = [1, 2, 3, 4, 5];
var sum = 0;

$.each(array, function() {
  sum += (this);
});
alert(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 14

adamjford
adamjford

Reputation: 7608

$.each(function) and $(...).each(function) both accurately perform the equivalent of a for-each loop, but the actual JavaScript for-each equivalent is the for(... in ...) loop.

for (variable in object)
{
    // code to be executed
}

http://www.w3schools.com/js/js_loop_for_in.asp

This isn't jQuery-specific, but hey, jQuery is just a JavaScript library after all. :)

Upvotes: 5

user142019
user142019

Reputation:

For an array, see Rionmonster's answer. For all items matchins a selector:

$("a").each(function() {
   alert($(this).attr('href'));
});

Upvotes: 4

Related Questions