A sample introduction to the for in traversal method in JavaScript

  • 2020-03-30 01:40:57
  • OfStack

Abstract: the loop counter of for-in traversal method is a string type. When traversing an object, it is the property/method name of the object. When traversing a number group, it is the index index of the array element.

In addition to the traditional for loop, JavaScript defines a for-in mode for traversing operations, which varies depending on the data source.
(1) traversal object:
 
var fish = { 
head : 1, 
tail : 1, 
} 
for(var prop in fish) { 
console.log(fish[prop]); 
} 

Debugging observation: prop in turn is 'head','tail', that is, when traversing the property of the object is the existence of the string type, the loop counter as the property name of the object.
(2) iterate over the groups
 
var arr = ['one', 'two', 'three']; 
for(var prop in arr) { 
console.log(prop); 
} 

Debugging observation: prop is '0','1', that is, when traversing the number group still exists as a string type, the difference is that the loop counter is the index of the array element. (try using the for loop at this point, and the result is consistent with the for-in)
If the code adds:
 
if(Object.prototype.clone === 'undefined') 
Object.prototype.clone = function() {}; 

The output is: 0,1,clone
If the output is in the for loop, it is still 0,1; In other words, the for-in loop iterates over the properties of the data source type of the current operation (clone is also output when the object fish is in for-in), so it requires pulling a string during the for-in traversal: if you only operate on the object's own properties, you need to remove the inherited properties, such as the hasOwnProperty() method.

Related articles: