Summary: The loop meter of the for-in traversal method is a string type. When traversing the object, it is an object attribute/method name, and the index of the array elements when traversing the array. Unlike the ordinary for cycle, the for-in will inherit the attributes of the inheritance attributes. /Methods list, this point needs to be specially concerned when used.
In addition to the traditional for loop, JavaScript defines the for-in method for the traversal operation, and there is a difference in use according to the data source.
(1) Traversing objects:
Copy code code as follows:
var Fish = {{
head: 1,
tail: 1,
}
for (var Prop in Fish) {
console.log (fish [prop]);
}
Observation during debugging: PROP is 'head', 'tail', that is, when traversing object attributes, the attribute name of the string type and the loop counter as the object.
(2) Traversing array
Copy code code as follows:
var arr = ['One', 'Two', 'Three'];
for (var prop in arr) {
console.log (prop);
}
Observation during debugging: PROP is '0', '1', that is, when the array traverses the array, it still exists in the string type. (At this time, you can try the loop output, the result is consistent with the for-in)
If the code is added:
Copy code code as follows:
If (Object.prototype.clone === 'Undefined')
Object.prototype.clone = Function () {};
The output result is: 0,1, clone
If the output output is used at this time, it is still 0,1; that is, the FOR-in loop will traverse the attributes of the type of data source in the current operation (also out of the object FISH with for-in, and the output will also output. CLONE, so it is required to pull a strings when using for-in all times: if you only operate the object's own attributes, you need to remove the inherited attributes, such as using the HasownProperty () method.