Home > Article > Web Front-end > Javascript determines whether there is a certain attribute instance code summary in the object
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,它将保持不变
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!