Abstract: The loop counter in the for-in traversal mode is of the string type. When the object is traversed, the object property/method name is used. When the array is traversed, the array element subscript index is used, which is different from the common for loop, for-in lists the inherited attributes/methods, which requires special attention during use.
In addition to the traditional for loop, JavaScript defines the for-in method for traversal operations. There are differences in use based on different data sources.
(1) traverse objects:
Copy codeThe Code is as follows:
Var fish = {
Head: 1,
Tail: 1,
}
For (var prop in fish ){
Console. log (fish [prop]);
}
During debugging, observe that the prop is 'head' and 'tail' in sequence. That is, when traversing object attributes, the property name of the object exists in the string type and the cyclic counter is.
(2) traverse the Array
Copy codeThe Code is as follows:
Var arr = ['one', 'two', 'three '];
For (var prop in arr ){
Console. log (prop );
}
During debugging, observe that the prop values are '0' and '1' in sequence, that is, the traversal array still exists in the string type. The difference is that the loop counter is the subscript of the array element. (In this case, you can try to use the for loop output. The result is consistent with that of for-in)
If the following code is added:
Copy codeThe Code is as follows:
If (Object. prototype. clone === 'undefined ')
Object. prototype. clone = function (){};
The output result is: 0, 1, clone
If the for loop is used for output, it is still 0, 1; that is, the for-in loop will traverse the attributes of the type of the data source to which the current operation belongs (when the for-in object is also used for fish, will also output clone), so you need to pull a string using the for-in time: if you only operate on the attributes of the object, you need to remove the inherited attributes, for example, use the hasOwnProperty () method.