Home > Web Front-end > JS Tutorial > body text

Introduction to 3 methods of traversing the properties of objects in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:23:15
Original
1148 people have browsed it

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:


Copy code The code is as follows:

var o = {x:1, y:2};
var a = Object.create(o);
a.z = 3;

for(p in a){
console.log(p);
}//z x y
console.log(Object.keys(a));//["z"]
console.log(Object.getOwnPropertyNames(a));//["z"]

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template