This article mainly introduces three methods for traversing the property of an object in JavaScript. This article first explains three methods and uses an image for better understanding, and then provides code examples, you can refer to the following three methods in JavaScript to traverse the property of an object:
1. for/in. You can use the for/in statement to traverse the object's Own property (Own Property) and the property inherited from the prototype object. only the property of enumerable can be traversed.
2. Object. keys (). You can pass an Object as a parameter to Object. keys (). the Object. keys () statement returns an array consisting of all property name strings. The Object. keys () statement only returns the Object's Own (Own Property) and enumerable property. This statement is only valid in the ECMAScript 5 standard.
3. Object. getOwnPropertyNames (). You can pass an Object as a parameter to Object. getOwnPropertyNames (). like Object. keys (), this statement returns an array consisting of all property name strings. Unlike Object. keys (), the Object. getOwnPropertyNames () statement returns the property (Own Property) of all objects, regardless of whether the Object is enumerable. This statement is only valid in the ECMAScript 5 standard.
The above information is summarized as follows:
Lab:
The code is as follows:
Var o = {x: 1, y: 2 };
Var a = Object. create (o );
A. z = 3;
For (p in ){
Console. log (p );
} // Z x y
Console. log (Object. keys (a); // ["z"]
Console. log (Object. getOwnPropertyNames (a); // ["z"]