📜  foreach jquery - Javascript (1)

📅  最后修改于: 2023-12-03 15:15:10.314000             🧑  作者: Mango

foreach in jQuery - Javascript

Foreach is a loop used to iterate over a collection of elements or values. In jQuery, the .each() method provides the implementation of the foreach loop. It can be used to iterate over arrays, objects, or jQuery collections.

Syntax

The syntax for using .each() method is as follows:

$(selector).each(function(index, element){
  // code to be executed for each iteration
});
  • selector: A string containing a selector expression or a jQuery object containing elements to be iterated over.
  • index: An optional parameter representing the index of the current iteration.
  • element: An optional parameter representing the current element being iterated over.
Examples
Example 1: Iterating over an array
let fruits = ["apple", "banana", "cherry", "orange"];

$.each(fruits, function(index, value){
  console.log(index + ": " + value);
});

Output:

0: apple
1: banana
2: cherry
3: orange
Example 2: Iterating over an object
let person = {name: "John", age: 30, city: "New York"};

$.each(person, function(key, value){
  console.log(key + ": " + value);
});

Output:

name: John
age: 30
city: New York
Example 3: Iterating over a jQuery collection
$(".fruits").each(function(index, element){
  console.log(index + ": " + $(element).text());
});

HTML:

<ul>
  <li class="fruits">apple</li>
  <li class="fruits">banana</li>
  <li class="fruits">cherry</li>
  <li class="fruits">orange</li>
</ul>

Output:

0: apple
1: banana
2: cherry
3: orange
Conclusion

The .each() method in jQuery provides a simple and easy way to iterate over collections in Javascript. It can be used to iterate over arrays, objects, or jQuery collections.