Discovered a clever implementation: you need to check whether an object (Object) is empty, that is, it does not contain any elements. An object in Javascript is a dictionary, which contains a series of key value pairs. Checking whether an object is empty is equivalent to checking whether there are key-value pairs in the object. Written as code, it looks like:
if (isEmptyObject(obj)) { // obj is empty } else { // not empty }
As for the implementation of isEmptyObject, there is a very creative way in jQuery, please see the code:
function isEmptyObject(obj) { for (var key in obj) { return false; } return true; }
Although Javascript does not provide the isEmpty() method natively, it does provide an iterator that can be used to traverse all key-value pairs. So what jQuery does is try to traverse. If there is any key-value pair, it means that the object is not empty, and it returns false directly. In terms of efficiency, since only one element is read, and at most there is some overhead of jumping out of the loop, the actual performance will not be much worse than the native method.
function isNullObj(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)){ return false; } } return true; }
The above is the entire content of this article, I hope you all like it.
For more related tutorials, please visit JavaScript Basics Tutorial