Possible Duplicate:
How do I test for an empty Javascript object from JSON?可能重复:如何从JSON测试空Javascript对象?
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:
在Javascript中是否有一种简单的方法来检查对象是否没有属性?或者换句话说,检查地图/关联数组是否为空的简单方法?例如,假设您有以下内容:
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 个解决方案
#1
42
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.
您的解决方案也可以工作,但前提是没有库扩展Object原型。它可能也可能不够好。
#1
42
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.
您的解决方案也可以工作,但前提是没有库扩展Object原型。它可能也可能不够好。