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 property2. 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 own3It can be judged by using undefined to judge its own attributes and inherited attributes. varO={x:1};o.x!==undefined;//trueo.y!==undefined;//falseo.tostring!==undefined//trueThere is a problem with this method, if the value of the property is undefined, the method cannot return the desired result, as follows. varo={x:undefined};o.x!==undefined;//False, the property exists, but the value is undefinedo.y!==undefined;//falseo.tostring!==undefined//true4. In a conditional statement, judge directlyvaro={};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