Home > Web Front-end > JS Tutorial > Summary of methods to determine whether a certain attribute exists in an object using javascript_javascript skills

Summary of methods to determine whether a certain attribute exists in an object using javascript_javascript skills

WBOY
Release: 2016-05-16 17:33:31
Original
1165 people have browsed it

There are several ways to detect the presence or absence of attributes in an object.
1. Use the in keyword
This method can determine whether the object's own properties and inherited properties exist.

Copy code The code is as follows:

var o={x:1};
"x" in o; //true, own property exists
"y" in o; //false
"toString" in o; //true, it is an inherited property

2. Use the hasOwnProperty() method of the object
This method can only determine whether its own properties exist, and will return false for inherited properties.
Copy code The code is as follows:

var o={x:1};
o.hasOwnProperty("x"); //true, there is x in the own property
o.hasOwnProperty("y"); //false, there is no y in the own property
o.hasOwnProperty(" toString"); //false, this is an inherited property, but not a self-owned property

3. Use undefined to judge
Both self-owned and inherited properties can be used judge.
Copy code The code is as follows:

var o={x:1};
o.x!==undefined; //true
o.y!==undefined; //false
o.toString!==undefined //true

There is a problem with this method, if If the value of the attribute is undefined, this method cannot return the desired result, as follows.
Copy code The code is as follows:

var o={x:undefined};
o.x!==undefined; //false, the attribute exists, but the value is undefined
o.y!==undefined; //false
o.toString!==undefined //true

4. Directly judge in the conditional statement
Copy the code The code is as follows:

var o={};
if(o.x) o.x =1; //If x is undefine, null, false, " ", 0 or NaN, it will remain unchanged
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