A simple way for JavaScript to determine whether an object {} is an empty object _javascript tips

Source: Internet
Author: User

When doing the project encountered a problem, to determine whether an object is empty object, found that this judgment can be, on the code:

1. Code 1:

var a = {};
if (!a) {console.log (1);}
else if (a = = null) {Console.log (2);} 
else {console.log (3);}

Results are: 3

2. Code 2:

var b = {};
if (b = = {}) {Console.log (4);}
if (b = = ' {} ') {Console.log (5);} 
if (typeof (b) = = ' object ') {Console.log (6);}

Results are: 6

3. Code 3:

var c = {};
if (json.stringify (c) = = "{}") {Console.log (7);}
var c = {};
if (json.stringify (c) = = "{}") {Console.log (7);}

Results are: 7

So you can use the method of code 3 to determine whether an object is an empty object {};

If the object is not empty, and you know that the object is not empty, an attribute (such as {id:111}) must exist, you can judge in this way:

4. Code 4:

var d = {};
var e = {id:111};
if (d.id) {Console.log (8);}
if (e.id) {Console.log (9);}

Results are: 9

Summary: obviously code 3 judgment way is more "strong", but the efficiency is obviously inferior to the Code 4 judgment method

The above is a small series for you to bring the JavaScript to determine whether an object {} is an empty object of the simple method of all content, I hope that we support the cloud Habitat Community ~

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.