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

耗尽温柔 提交于 2019-11-29 02:14:28

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/3426979/javascript-checking-if-an-object-has-no-properties-or-if-a-map-associative-arra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!