What is equivalent to for-each loop in jQuery?

I recently started working with jQuery and wondered how I would iterate over a collection (array or list of elements) of elements and summarize their contents.

Does jQuery have something like a for loop, like so many other languages?

Will there be an easy way to implement this - if it is not easy to do?

+3
source share
3 answers

What you are looking for is a jQuery function each()that allows you to iterate through any given fields and perform an action.

Application:

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>
Run codeHide result
+14
source

$.each(function) $(...).each(function) for-each, JavaScript for(... in ...).

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

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

jQuery, hey, jQuery - JavaScript.:)

+5

For an array, see Rionmonster's answer. For all matchins elements, the selector:

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

Source: https://habr.com/ru/post/1783727/


All Articles