Javascript:检查对象是否没有属性或者映射/关联数组是否为空
在 Javascript 中是否有一种简单的方法来检查对象是否没有属性?或者换句话说,有一种简单的方法来检查映射/关联数组是否为空?例如,假设您有以下内容:
var nothingHere = {};
var somethingHere = {foo: "bar"};
有没有一种简单的方法可以判断哪个是“空”?我唯一能想到的是这样的:
function isEmpty(map) {
var empty = true;
for(var key in map) {
empty = false;
break;
}
return empty;
}
有没有更好的方法(比如原生属性/函数之类的)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
您的解决方案也有效,但前提是没有扩展
Object
原型的库。它可能不够好,也可能不够好。Try this:
Your solution works, too, but only if there is no library extending the
Object
prototype. It may or may not be good enough.