JavaScript, detecting whether a property exists in an object

Source: Internet
Author: User
Tags hasownproperty

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.