开发者

Javascript: Checking if an object has no properties or if a map/associative-array is empty [duplicate]

开发者 https://www.devze.com 2023-01-10 08:36 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How do I test for an empty Javascript object from JSON?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How do I test for an empty Javascript object from JSON?

Is there an easy way to check if an object has no properties, in Javascript? Or in other words, an easy way to check if a map/associative array is empty? For example, let's say you had the following:

开发者_如何转开发var nothingHere = {};
var somethingHere = {foo: "bar"};

Is there an easy way to tell which one is "empty"? The only thing I can think of is something like this:

function isEmpty(map) {
   var empty = true;

   for(var key in map) {
      empty = false;
      break;
   }

   return empty;
}

Is there a better way (like a native property/function or something)?


Try this:

function isEmpty(map) {
   for(var key in map) {
     if (map.hasOwnProperty(key)) {
        return false;
     }
   }
   return true;
}

Your solution works, too, but only if there is no library extending the Object prototype. It may or may not be good enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消