You can use several methods to determine whether an attribute exists in an object.
1. Use the in keyword
This method can be used to determine whether an object's own attributes and inherited attributes exist.
The Code is as follows:
Var o = {x: 1 };
"X" in o; // true, self-owned attribute exists
"Y" in o; // false
"ToString" in o; // true, is an inherited property
2. Use the hasOwnProperty () method of the object
This method can only determine whether a property exists. If an inherited property exists, false is returned.
The Code is as follows:
Var o = {x: 1 };
O. hasOwnProperty ("x"); // true, which has x
O. hasOwnProperty ("y"); // false. y does not exist in the property.
O. hasOwnProperty ("toString"); // false, which is an inherited property but not a self-owned property
3. Use undefined to determine
Both self-owned and inherited attributes can be determined.
The Code is as follows:
Var o = {x: 1 };
O. x! = Undefined; // true
O. y! = Undefined; // false
O. toString! = Undefined // true
This method has a problem. If the attribute value is undefined, this method cannot return the expected results, as shown below.
The Code is as follows:
Var o = {x: undefined };
O. x! = Undefined; // false: The property exists, but the value is undefined.
O. y! = Undefined; // false
O. toString! = Undefined // true
4. Directly judge in the Condition Statement
The Code is as follows:
Var o = {};
If (o. x) o. x + = 1; // if x is undefine, null, false, "", 0 or NaN, it remains unchanged