Home >Web Front-end >JS Tutorial >How to use each function in js
In JavaScript, there is no built-in each function, but the jQuery library provides a very useful $.each() function for traversing arrays or objects. If you are using jQuery, or your environment includes jQuery, you can use the $.each() function like this.
Traverse the array
javascript
##
var array = [ "item1", "item2", "item3" ]; $.each(array, function(index, value) { console.log(index + ": " + value); });
In the above example, $.each() traverses the array array. For each element in the array, it calls the provided function, passing the index and value of the current element as arguments.
Traverse the object
javascript
##var object = {
key1: "value1",
key2: "value2",
key3: "value3"
};
$.each(object, function(key, value) {
console.log(key + ": " + value);
});
at In this example, $.each() iterates over the object object. For each property in the object, it calls the provided function, passing the current property's key and value as arguments.
The above is the detailed content of How to use each function in js. For more information, please follow other related articles on the PHP Chinese website!