Everyone knows that JavaScript provides two ways to iterate objects:
(1) for loop;
(2) for..in loop;
Use for loop to iterate array objects. I think everyone has already It's commonplace. However, when using for..in loops, everyone should pay attention. Why do you say this? Everyone, listen to me...
Javascript provides a special loop (that is, the for..in loop), which is used to iterate the properties of an object or each element of an array, for...in The loop counter in the loop is a string, not a number. It contains the name of the current property or the index of the current array element.
Case 1:
//Use for.. in loop traverses the object attributes
varperson={
name: "Admin",
age: 21,
address: "shandong"
};
for(vari in person){
console.log(i);
}
The execution result is:
name
age
address
When traversing an object, the variable i means that the loop counter is the attribute name of the object
// Use for..in loop to traverse the array
vararray = ["admin","manager","db"]
for(vari in array){
console.log(i);
}
Execution result:
0
1
2
When traversing an array, the variable i, which is the loop counter, is the index of the current array element
Case 2:
However, it seems that the for.. in loop is quite useful now, but don’t be too happy too early. Take a look at the following example:
var array =["admin","manager","db"];
//Add a prototype to Array name attribute
Array.prototype.name= "zhangsan";
for(var i in array){
alert(array[i]);
}
Running results:
admin
manager
db
zhangsan
Hey, it’s a wonder, how come zhangsan appears for no reason
Now, let’s see what happens when using a for loop?
vararray = ["admin","manager"," db"];
//Add a name attribute to the prototype of Array
Array.prototype.name = "zhangsan";
for(var i =0 ; i
alert(array[i]);
};
Run result:
admin
manager
db
Oh, now I understand, for. The .in loop will traverse the methods and properties in the prototype of a certain type, so this may cause unexpected errors in the code. In order to avoid this problem, we can use the object's hasOwnProperty() method to avoid this problem. If the object's properties or methods are non-inherited, then the hasOwnProperty() method returns true. That is, the check here does not involve properties and methods inherited from other objects, but only properties created directly in the specific object itself.
Case 3:
vararray = ["admin" ,"manager","db"];
Array.prototype.name= "zhangshan";
for(vari in array){
//If it is not an attribute directly created by the object itself (that is, The property // is an attribute in the prototype), then skip the display
if(!array.hasOwnProperty(i)){
continue;
}
alert(array[i]);
}
Run results:
admin
manager
db
Everything is as good as before. Hey, I don’t know, what do comrades feel after reading this? Doesn’t it feel like “the clouds and mist are parted to see the sunny sky”, haha