Javascript:检查对象是否没有属性或映射/关联数组是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3426979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Checking if an object has no properties or if a map/associative-array is empty
提问by Vivin Paliath
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:
有没有一种简单的方法可以在 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)?
有没有更好的方法(比如本地属性/函数或其他东西)?
回答by chryss
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 Objectprototype. It may or may not be good enough.
您的解决方案也有效,但前提是没有扩展Object原型的库。它可能不够好,也可能不够好。

