JS to judge an instance of an empty object (super simple) _javascript technique

Source: Internet
Author: User

Recently, the project encountered a problem of judging empty objects, consult the relevant data and then summarize.

It is not better to judge an empty object than to judge an empty string, because an empty object is also an object that needs to be allocated separately, rather than a large pot of rice like a string, and everyone is equal, the following code:

As you can see in the code, an empty object created by an object literal or an empty object created by the object constructor is not equal to each other.

1. Convert objects to strings for comparison

This method is not recommended, but it is indeed the most easy to think of, the main use of json.stringify () This method to the object for a strong turn, posted out for a look only:

var a={};
 var b=new Object ();
 Console.log ("Comparison of object literals:" + (json.stringify (a) = = "{}")
 Console.log ("Comparison of Constructors:" + (json.stringify (b) = = "{}")

We can get two null objects converted to string after the comparison is true, can solve this problem, but not recommended, the second method.

2.for in loop

The For In loop allows you to iterate through all the properties to determine whether an object is an empty object at a time:

var a={};
var b=new Object ();
function Isemptyobject (obj) {for

   [var key in obj] {return
     false
   };
   return True
};
if (Isemptyobject (a)) {
   alert ("A is an empty object")
}
if (Isemptyobject (b)) {
   alert ("B is an empty object")
}

Loops the property when the object is cycled using a for in loop, and the corresponding array loops with the subscript, such as:

var b = [' Hello ', ' my ', ' World ' for '
(var index in b) {
   console.log (B[index]);
}
Hello my World

The above is a small series for everyone to bring the (title) all the content, I hope that we support the cloud-Habitat Community ~

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.