The trick in JavaScript to determine whether an object is empty _javascript

Source: Internet
Author: User

A clever implementation was found: it was necessary to check whether an object was empty, that is, not containing any elements. The object in Javascript is a dictionary that contains a series of key value pairs (key values Pair). Checking whether an object is empty is equivalent to checking that there is no key value pair in the object. Written in code, as in the form of:

if (Isemptyobject (obj)) {

 //obj is empty
} else {
 //not empty
} 

As for the implementation of Isemptyobject, there is a very thoughtful way in jQuery, see the code:

function Isemptyobject (obj) {for
 [var key in obj] {return
 false;
 }
 return true;
}

Although Javascript does not provide a native IsEmpty () method, it provides an iterator that can be used to traverse all key-value pairs. So what JQuery does is try to traverse it, and if there is any key-value pair, that means the object is non-null, return it directly to false. In terms of efficiency, because only read one element, plus some out of the loop overhead, the actual performance is not much worse than the native method. This is a very ingenious implementation.

Note: Some netizens point out that ES5 provides a object.getownpropertynames method to get all the element keys. Its return value is an array that, when the length of the array is zero, indicates that the object is empty.

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.