Absrtact: The loop counter of the for-in traversal is a string type, which, when traversing an object, is the object property/method name, and the array element subscript index when traversing it, unlike the normal for loop, for-in lists the inherited properties/methods, which require special attention when used.
In addition to the traditional for loop, JavaScript defines the for-in for traversal operations, and differs in usage depending on the data source.
(1) Traversing the object:
Copy Code code as follows:
var fish = {
Head:1,
Tail:1,
}
For (var prop in fish) {
Console.log (Fish[prop]);
}
When debugging observe: Prop in turn is ' head ', ' tail ', that is, when traversing object properties is a string type exists, the loop counter is the object's property name.
(2) traversing the array
Copy Code code as follows:
var arr = [' One ', ' two ', ' three '];
For (Var prop in arr) {
Console.log (prop);
}
observed during debugging: Prop is ' 0 ', ' 1 ', which is still in the string type when traversing the array, and the loop counter is the subscript for the array element. (You can try the For loop output at this point and the result is consistent with for-in)
If the code adds:
Copy Code code as follows:
if (Object.prototype.clone = = ' undefined ')
Object.prototype.clone = function () {};
The output result is: 0,1,clone
If you use the For loop output at this point, you are still 0, 1, that is, the for-in loop loops through the attributes of the type that the data source of the current operation has (also output clone when the object fish uses for-in), So it requires the use of for-in to pull a string: If only the object owned property operations, you need to remove inherited attributes, such as the hasOwnProperty () method.