The each method is also widely used in jQuery source code. In fact, the each method in jQuery is implemented through the call method in js. The following describes the call method.
The call method is amazing. In fact, the official explanation is: "call a method of an object and replace the current object with another object ." The explanation on the Internet is to change the context, or change the context this pointer.
Copy codeThe Code is as follows:
Call ([thisObj [, arg1 [, arg2 [, [,. argN])
Parameters
ThisObj is optional. Will be used as the object of the current object.
Arg1, arg2, and argN are optional. The method parameter sequence will be passed.
The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj.
Example
Copy codeThe Code is as follows:
Function add (a, B)
{
Alert (a + B );
}
Function sub (a, B)
{
Alert (a-B );
}
Add. call (sub, 3, 1 );
Use add to replace sub, add. call (sub, 3, 1) = add (3, 1), so the running result is: alert (4 );
Note: Functions in js are actually objects, and Function names are references to Function objects.
More in-depth call is not mentioned here.
The following describes some common usage of jQuery's each method.
Copy codeThe Code is as follows:
Var arr = ["one", "two", "three", "four"];
$. Each (arr, function (){
Alert (this );
});
The above each output results are: one, two, three, four
Copy codeThe Code is as follows:
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, and item is equivalent to taking every one-dimensional array,
Item [0] is relative to the first value in each one-dimensional array.
Therefore, the above each output is: 1 4 7
Copy codeThe Code is as follows:
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 can loop through every attribute.
Output result: 1 2 3 4