Summary: The loop counter of the for-in traversal method is of string type. When traversing the object, it is the object attribute/method name. When traversing the array, it is the array element subscript index. Unlike the ordinary for loop, for-in will inherit the attributes. / method is listed, this needs special attention when using it.
In addition to the traditional for loop, JavaScript defines a for-in method for traversal operations. There are differences in usage depending on the data source.
(1) Traverse objects:
var fish = {
head : 1,
tail : 1,
}
for(var prop in fish) {
console.log(fish[prop]);
}
Observe during debugging: props are 'head', 'tail' in order, that is, when traversing the object properties, they exist in string type, and the loop counter is the property name of the object.
(2) Traverse the array
var arr = [ 'one', 'two', 'three'];
for(var prop in arr) {
console.log(prop);
}
Observe while debugging : prop is '0', '1' in sequence, that is, it still exists in string type when traversing the array. The difference is that the loop counter is the subscript of the array element. (At this time, you can try using a for loop to output, the result is consistent with for-in)
If you add to the code:
if(Object.prototype.clone === 'undefined')
Object.prototype.clone = function() {};
The output result is: 0,1,clone
If you use a for loop to output, it will still be 0,1; that is to say, the for-in loop will use the attributes of the type of the data source currently operated Traversing out (Similarly, when using for-in on the object fish, clone will also be output), so it is required to pull a string when using for-in to traverse: If you only operate on the object's own attributes, you need to use the inherited attributes Eliminate them, such as using the hasOwnProperty() method.