📅  最后修改于: 2023-12-03 14:43:18.227000             🧑  作者: Mango
The jQuery each()
function is a powerful tool for iterating through arrays and objects in JavaScript. This function allows you to easily loop through each element of an array or property of an object, performing a specific action on each iteration.
The syntax for the each()
function is as follows:
$.each(arrayOrObject, function(index, value) {
// Perform action on each iteration
});
The arrayOrObject
parameter can be either an array or an object. The function
parameter is a callback function that is executed for each iteration of the loop. The index
parameter refers to the index of the current element in the array or property of the current object being processed. The value
parameter refers to the value of the current element in the array or property of the current object being processed.
var array = ["apple", "orange", "banana"];
$.each(array, function(index, value) {
console.log(index + ": " + value);
});
// Output:
// 0: apple
// 1: orange
// 2: banana
var object = {name: "John", age: 30, city: "New York"};
$.each(object, function(key, value) {
console.log(key + ": " + value);
});
// Output:
// name: John
// age: 30
// city: New York
var array = ["apple", "orange", "banana"];
$.each(array, function(index, value) {
array[index] = value.toUpperCase();
});
console.log(array);
// Output:
// ["APPLE", "ORANGE", "BANANA"]
var object = {name: "John", age: 30, city: "New York"};
$.each(object, function(key, value) {
object[key] = value.toUpperCase();
});
console.log(object);
// Output:
// {name: "JOHN", age: "30", city: "NEW YORK"}
The jQuery each()
function is a powerful tool for iterating through arrays and objects in JavaScript. By using this function, you can easily loop through each element of an array or property of an object, performing a specific action on each iteration. With its ease of use and versatility, the each()
function is a valuable addition to any JavaScript programmer's toolkit.