Home > Web Front-end > JS Tutorial > body text

JS/Jquery method to determine if an object is empty

PHPz
Release: 2018-10-12 16:00:37
Original
1308 people have browsed it

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
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

The above is the entire content of this article, I hope you all like it.

For more related tutorials, please visit JavaScript Basics Tutorial

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template