Whether a property judgment method exists in the JavaScript detection object

Source: Internet
Author: User
Tags tostring hasownproperty

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

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.