Whether a property determination method exists in the javascript detection object

Source: Internet
Author: User
Tags hasownproperty

You can use several methods to determine whether an attribute exists in an object.

1. Use the in keyword

This method can be used to determine whether an object's own attributes and inherited attributes exist.

The Code is as follows:

Var o = {x: 1 };

"X" in o; // true, self-owned attribute 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 a property exists. If an inherited property exists, false is returned.

The Code is as follows:

Var o = {x: 1 };

O. hasOwnProperty ("x"); // true, which has x

O. hasOwnProperty ("y"); // false. y does not exist in the property.

O. hasOwnProperty ("toString"); // false, which is an inherited property but not a self-owned property

3. Use undefined to determine

Both self-owned and inherited attributes can be determined.

The Code is as follows:

Var o = {x: 1 };

O. x! = Undefined; // true

O. y! = Undefined; // false

O. toString! = Undefined // true

This method has a problem. If the attribute value is undefined, this method cannot return the expected results, as shown below.

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. Directly judge in the Condition Statement

The Code is as follows:

Var o = {};

If (o. x) o. x + = 1; // if x is undefine, null, false, "", 0 or NaN, it remains 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.