The existence or absence of attributes in the detection object can be judged by several methods.
1. Use the IN keyword.
This method can determine whether an object's own property and inherited attributes exist.
varO={x:1};"X"inchO//true, owning property exists"Y"inchO//false"ToString"inchO//true, is an inherited property
2. Use the hasOwnProperty () method of the object.
The method can only determine if its own property exists and returns false for the inherited property.
varO={x:1};o.hasownproperty ("X");//true, there is an X in its own propertyO.hasownproperty ("Y");//false, there is no y in the own propertyO.hasownproperty ("toString");//false, which is an inherited property, but not a property of its own
3. Judging with undefined
Both own and inherited properties can be judged.
varO={x:1};o.x!==undefined;//trueo.y!==undefined;//falseo.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.
var o={x: Undefined};o.x !==undefined; //false, property exists, But the value is undefined o.y!==undefined; // false o.tostring!==undefined // true
4. Directly judging 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
JavaScript, detecting whether a property exists in an object