Home > Article > Web Front-end > js method to determine whether there is an attribute
This article mainly shares with you the method of judging whether there are attributes in js. I hope it can help everyone.
Accessing object properties
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,是一个继承属性
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,这是一个继承属性,但不是自有属性
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
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
4. Directly judge in the conditional statement
var o={}; if(o.x) o.x+=1; //如果x是undefine,null,false," ",0或NaN,它将保持不变
Access object properties
1. Use 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,是一个继承属性
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,这是一个继承属性,但不是自有属性
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
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
4. Directly judge in the conditional statement
var o={}; if(o.x) o.x+=1; //如果x是undefine,null,false," ",0或NaN,它将保持不变
Related recommendations:
Learn to understand the tag attribute of script in javascript
How to dynamically create tags and set attributes in js
What are the three attributes of a javascript object
The above is the detailed content of js method to determine whether there is an attribute. For more information, please follow other related articles on the PHP Chinese website!