As you know, there are two ways to iterate objects in javascript:
(1) for loop;
(2) for. in circulation;
Using a For loop to iterate over a group of objects must have been commonplace. However, use for.. In the cycle, we should pay attention to, why do you say so? Listen to me.
JavaScript provides a special kind of loop (that is, for. In loop, to iterate over the attributes of an object or each element of an array, the loop counter in the for...in loop is a string, not a number. that contains the name of the current property or the index of the current array element.
Case one:
Copy Code code as follows:
Use for.. In loop traversal of object properties
varperson={
Name: "Admin",
Age:21,
Address: "Shandong"
};
For (vari in person) {
Console.log (i);
}
The results of the execution are:
Name
Age
Address
When traversing an object, the variable i, the loop counter, is the property name of the object
Copy Code code as follows:
Use for.. In loop traversal array
Vararray = ["admin", "manager", "DB"]
For (Vari in array) {
Console.log (i);
}
Execution results:
0
1
2
When traversing an array, the variable i, the loop counter, is the index of the current array element
Case TWO:
But now it appears for. The in loop is pretty good, but don't be too happy to take a look at the following example:
Copy Code code as follows:
var array =["admin", "manager", "DB";
Add a Name property to the array's prototype
Array.prototype.name= "Zhangsan";
for (var i in array) {
Alert (Array[i]);
}
Run Result:
Admin
Manager
Db
Zhangsan
Gee, wonders, how come out of nowhere for a Zhangsan
Now, what about using the For loop?
Copy Code code as follows:
Vararray = ["admin", "manager", "DB"];
Add a Name property to the array's prototype
Array.prototype.name = "Zhangsan";
for (var i =0; i<array.length; i++) {
Alert (Array[i]);
};
Run Result:
Admin
Manager
Db
Oh, now I see, for. The in loop loops through the methods and attributes in a type of prototype (prototype), so this can cause unexpected errors in your code. To avoid this problem, we can use the hasOwnProperty () method of the object to avoid this problem, and the hasOwnProperty () method returns True if the object's properties or methods are inheritable. That is, the check here does not involve properties and methods inherited from other objects, only the properties that are created directly in the specific object itself.
Case THREE:
Copy Code code as follows:
Vararray = ["admin", "manager", "DB"];
Array.prototype.name= "Zhangshan";
For (Vari in array) {
If it is not a property created directly by the object itself (that is, the genus//sex is a property in the prototype), skip the display
if (!array.hasownproperty (i)) {
Continue
}
Alert (Array[i]);
}
Run Result:
Admin
Manager
Db
Everything is as good as ever, ah, do not know, comrades have seen what feelings, is not a kind of "clear clouds see sunny" feeling ah, hehe