Home > Article > Web Front-end > Introduction to 3 methods of traversing the properties of objects in JavaScript_javascript skills
In JavaScript, you can use three methods to traverse the properties of an object:
1.for/in. You can use the for/in statement to traverse the object's own property (Own Property) and the properties it inherits from the prototype object. Only enumerable properties will be traversed.
2.Object.keys(). You can pass an object into Object.keys() as a parameter, and the Object.keys() statement will return 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 will return an array composed of all property name strings. Unlike Object.keys(), the Object.getOwnPropertyNames() statement will return the property (Own Property) of all objects themselves, regardless of whether they are enumerable. This statement is only valid in the ECMAScript 5 standard.
Based on the above information, the summary is as follows:
Experiment:
for(p in a){
console.log(p);
}//z x y
console.log(Object.keys(a));//["z"]
console.log(Object.getOwnPropertyNames(a));//["z"]