Each method takes the object to be traversed and the corresponding callback function as a parameter, and it acts as:
1. If the object to be traversed is an array-like form (judging by whether the type of the object's Length property value is number type), then the object to be traversed is the execution environment, and the callback function is placed in the execution environment to loop the execution length;
2, if the object to be traversed is not similar to an array, then use the method of the for-key in obj loop executes the callback function key, the same as the object to be traversed for the execution environment, the callback function in the execution environment to loop execution.
functionEach (elements, callback) {//parameters that define the callback function for eachvarI, Key//if the length of the elements parameter is a number type, it may be an array, a string, a arguments object, and so onif(typeofElements.length = = "Number") { for(i = 0; i < elements.length; i++)//Call (Thisobj,arg1,arg2,....); The first parameter is the execution environment object, followed by the data passed//if the callback function is in the execution environment of Elements[i], the result of using both parameters I and Elements[i] is null, undefined, then elements is returnedif(Callback.call (Elements[i], I, elements[i]) = = =false)returnelements}Else { for(Keyinchelements)if(Callback.call (Elements[key], key, elements[key]) = = =false)returnelements}returnelements};
The usage is simple, so we don't give an example.
Because I'm learning this, I want to know how to output this in a callback function, so I played it this way:
var o = {"A": "Sdfsdf", "S": 3};each (o,function(i,ele) {console.log ( This );});
The Console.log console in Google Chrome actually gets the result: String {0: "S", 1: "D", 2: "F", 3: "S", 4: "D", 5: "F", Length:6, [[Primitivevalue]]: "SD Fsdf "}
This is because the execution environment of the callback function is Elements[key], in this case the o[a], and the first traversal of the passed parameter is O[a], and the value of O[a] is a string "sdfsdf", then this is naturally pointed to the string object
When you output a string in the console console as an object, you naturally get the object's property tree, but if you use the document.write output in an HTML page, you get the value of the string;
The following examples demonstrate:
function Test () { Console.log (this);} var str = "SDFSDFSDF"; Test.call (str); // obtained in the console: String {0: "S", 1: "D", 2: "F", 3: "S", 4: "D", 5: "F", 6: "S", 7: "D", 8: "F", Length:9, [[Primitivevalue]]: "Sdfsdfsdf"}// Output The value of the string in the HTML page: Sdfsdfsdf
Learn notes from each method in the Zepto.1.1.6.js source code