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 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

Related Article

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.