Detection of the existence of attributes in an object can be judged by several methods.
1. Use in keyword
This method can be used to determine whether an object's own properties and inherited properties exist.
The code is as follows:
var o={x:1};
"X" in O; True, own property 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 its own property exists and returns false for inherited properties.
The code is as follows:
var o={x:1};
O.hasownproperty ("X"); True, there is an X in its own property
O.hasownproperty ("Y"); False, there is no y in its own property
O.hasownproperty ("toString"); False, this is an inherited property, but not its own property
3. Judge with undefined
Both own and inherited properties can be judged.
The code is as follows:
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 property is undefined, the method cannot return the desired result, as follows.
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. Direct Judgment in conditional statements
The code is as follows:
var o={};
if (o.x) o.x+=1; If X is Undefine,null,false, "", 0 or Nan, it will remain unchanged