Home > Web Front-end > JS Tutorial > Javascript determines whether there is a certain attribute instance code summary in the object

Javascript determines whether there is a certain attribute instance code summary in the object

伊谢尔伦
Release: 2017-07-21 11:49:19
Original
1347 people have browsed it

1. Use the in keyword

This method can determine whether the object's own properties and inherited properties exist.

var o={x:1}; 
"x" in o; //true,自有属性存在 
"y" in o; //false 
"toString" in o; //true,是一个继承属性
Copy after login

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.

var o={x:1}; 
o.hasOwnProperty("x");    //true,自有属性中有x 
o.hasOwnProperty("y");    //false,自有属性中不存在y 
o.hasOwnProperty("toString"); //false,这是一个继承属性,但不是自有属性
Copy after login

3. Use undefined to judge
Both own properties and inherited properties can be judged.

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

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

var o={x:undefined}; 
o.x!==undefined; //false,属性存在,但值是undefined 
o.y!==undefined; //false 
o.toString!==undefined //true
Copy after login

4. Directly judge in the conditional statement

var o={}; 
if(o.x) o.x+=1; //如果x是undefine,null,false," ",0或NaN,它将保持不变
Copy after login


The above is the detailed content of Javascript determines whether there is a certain attribute instance code summary in the object. For more information, please follow other related articles on the PHP Chinese website!

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