Examples of several common ways to use jquery each

  • 2020-03-30 01:27:15
  • OfStack

JQuery source code itself has a lot of use of each method. In fact, each method in jQuery is implemented through the call method in js. The following is a brief introduction to the call method.

Call is a wonderful method, but the official description is: "call a method of an object to replace the current object with another object." More often than not, the explanation on the web is to change the context, or to change the context of this pointer.


call([thisObj[,arg1[, arg2[,   [,.argN]]]]])


parameter

ThisObj  Optional. Will be used as the object of the current object.
Arg1, arg2,   ArgN  Optional. A sequence of method parameters will be passed.

The call method can be used to call a method instead of another object. The call method changes the object context of a function from its original context to a new object specified by thisObj.

example


function add(a,b)   
{   
    alert(a+b);   
}   
function sub(a,b)   
{   
    alert(a-b);   
}   
add.call(sub,3,1);  


Replace sub with add, add.call(sub,3,1) == add(3,1), so the result is: alert(4);
Note: the Function in js is actually an object, and the Function name is a reference to the Function object.
The specific call is not mentioned here.

Here are a few common USES of jQuery's each method


 var arr = [ "one", "two", "three", "four"];     
 $.each(arr, function(){     
    alert(this);     
 });  
 

The output of each above is: one,two,three,four


var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]     
$.each(arr1, function(i, item){     
   alert(item[0]);     
});  

Arr1 is actually a two dimensional array, and item is equivalent to taking each one dimensional array, & PI;  
Item [0] versus taking the first value of each one-dimensional array & PI;  
So the top each output is: 1& PI;   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, and loops through each property & PI;      
The output is: 1    2   3   4


Related articles: