Home >Web Front-end >JS Tutorial >How to use each function in js

How to use each function in js

小老鼠
小老鼠Original
2024-03-13 16:26:051166browse

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.

Note

  • If you want to iterate over an array or object without using jQuery, you can use native JavaScript methods , such as Array.prototype.forEach() for arrays, or the for...in loop for objects.

  • When using $.each(), make sure your environment already contains the jQuery library, otherwise this function will not be available.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn