Home  >  Article  >  Web Front-end  >  jQuery $.each traverses objects and array usage examples_jquery

jQuery $.each traverses objects and array usage examples_jquery

WBOY
WBOYOriginal
2016-05-16 16:03:45958browse

Through it, you can traverse the attribute values ​​​​of objects and arrays and process them.

Instructions for use

The effects of each function are not completely consistent depending on the type of parameters:

1. Traverse objects (with additional parameters)

Copy code The code is as follows:

$.each(Object, function(p1, p2) {

this; //This here points to the current attribute value of the Object in each traversal
p1; p2; //Access additional parameters

}, ['Parameter1', 'Parameter2']);


2. Traverse the array (with attachment parameters)

Copy code The code is as follows:

$.each(Array, function(p1, p2){

this; //This here points to the current element of Array in each traversal
p1; p2; //Access additional parameters
}, ['Parameter 1', 'Parameter 2']);


3. Traverse objects (no additional parameters)

Copy code The code is as follows:

$.each(Object, function(name, value) {

this; //this points to the value of the current attribute
Name; //name represents the name of the current property of the Object
value; //value represents the value of the current property of the Object
});
[code]

4. Traverse the array (no additional parameters)
[code]
$.each(Array, function(i, value) {

this; //this points to the current element
i; //i represents the current subscript of Array
value; //value represents the current element of Array

});


Here are some common uses of jQuery’s each method

Copy code The code is as follows:

var arr = [ "one", "two", "three", "four"];
$.each(arr, function(){  
alert(this);
});  
//The output results of each above are: one, two, three, four
 
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] 
$.each(arr1, function(i, item){ 
alert(item[0]);
}); 
//In fact, arr1 is a two-dimensional array, item is equivalent to taking each one-dimensional array,
//item[0] is relative to taking the first value in each one-dimensional array
//So the output of each above is: 1 4 7


var obj = { one:1, two:2, three:3, four:4}; 
$.each(obj, function(key, val) { 
alert(obj[key]);
});
//This each is even more powerful, it can cycle through every attribute
//The output result is: 1 2 3 4
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