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