In the JavaScript for.. Introduction to in loop trap

  • 2020-03-29 23:41:12
  • OfStack

As you all know, there are two ways to iterate over objects in JavaScript:
(1) for loop;
(2) the for... In circulation;
Iterating over array objects using a for loop is not uncommon. However, use for.. In the loop, you have to be careful. Why do you say that? Listen to me...
Javascript provides a special loop (i.e., for..) In loop), used to iterate over each element of an object's attributes or array, for... The loop counter in the in loop is a string, not a number. It contains the name of the current attribute or the index of the current array element.
Case 1:
 
//Use for.. The in loop traverses the object properties
varperson={ 
name: "Admin", 
age: 21, 
address:"shandong" 
}; 
for(vari in person){ 
console.log(i); 
} 

The execution result is:
The name
The age
The address
When traversing an object, the variable I is the property name of the loop counter
 
//Use for.. The in loop iterates through the groups
vararray = ["admin","manager","db"] 
for(vari in array){ 
console.log(i); 
} 

Execution results:
0
1
2
When traversing an array, the variable I is the index of the loop counter for the current array element
Case 2:
But now it seems for.. The in loop works fine, but don't count your blessings. Here's an example:
 
var array =["admin","manager","db"]; 
//Add a name attribute to the Array stereotype
Array.prototype.name= "zhangsan"; 
for(var i in array){ 
alert(array[i]); 
} 

Operation results:
The admin
The manager
The db
zhangsan
Gee, the spectacle, how out of nothing a zhangsan
Now, what happens when you use a for loop?
 
vararray = ["admin","manager","db"]; 
//Add a name attribute to the Array stereotype
Array.prototype.name = "zhangsan"; 
for(var i =0 ; i<array.length; i++){ 
alert(array[i]); 
}; 

Operation results:
The admin
The manager
The db
Oh, I see now, for... The in loop iterates over the methods and properties of a certain type of prototype, so this can lead to unexpected errors in the code. To avoid this problem, we can avoid this problem by using the hasOwnProperty() method of the object, which returns true if the object's properties or methods are non-inherited. That is, the checks here do not involve properties and methods inherited from other objects, only properties created directly in the particular object itself.
Case 3:
 
vararray = ["admin","manager","db"]; 
Array.prototype.name= "zhangshan"; 
for(vari in array){ 
// If the property is not directly created by the object itself (that is, the genus) // Sex is an attribute in the stereotype), skipping the display  
if(!array.hasOwnProperty(i)){ 
continue; 
} 
alert(array[i]); 
} 

Operation results:
The admin
The manager
The db
Everything is good as before again, ah, do not know, comrades see what feeling, is there a kind of "clear the clouds see the sunny day" feeling, ha ha

Related articles: