📜  jquery 每个数组对象 - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:18.227000             🧑  作者: Mango

Introduction to jQuery each() for Arrays and Objects in JavaScript

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.

Syntax

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.

Examples
Iterating through an Array
var array = ["apple", "orange", "banana"];

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

// Output:
// 0: apple
// 1: orange
// 2: banana
Iterating through an Object
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
Modifying an Array
var array = ["apple", "orange", "banana"];

$.each(array, function(index, value) {
  array[index] = value.toUpperCase();
});

console.log(array);

// Output:
// ["APPLE", "ORANGE", "BANANA"]
Modifying an Object
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"}
Conclusion

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.