开发者

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

开发者 https://www.devze.com 2023-02-02 22:45 出处:网络
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.

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-ab开发者_运维百科le?


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>


$.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. :)


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号