If I set an object using:
var a = {};
or
var a = new Object();
How can I test whether or not it has anything inside it if I don't know specifically what to test for.开发者_如何转开发
(something like a == {}, but this does not evaluate correctly)
You could use this simple function:
function isEmpty(object) {
for(var property in object) {
if(object.hasOwnProperty(property))
return false;
}
return true;
}
But if you use jQuery: http://api.jquery.com/jQuery.isEmptyObject/
This can seem an innocent question, a simple solution as the one @SiteSafeNL provides could seem to work, but there is an implementation bugs that is not taken in account, the IE {DontEnum} Bug.
If you target IE8 and below you will need to implement something like this:
var isEmpty = (function () {
var hasOwn = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{toString:0}.propertyIsEnumerable("toString"),
dontEnums = ['toString', 'toLocaleString',
'valueOf', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable',
'constructor'];
return function (o) {
for (var p in o) {
if (hasOwn.call(o, p))
return false
}
if (hasDontEnumBug) { // IE8 and below
var i = dontEnums.length;
while(i--) {
if (hasOwn.call(o, dontEnums[i]))
return false;
}
}
return true;
};
})();
Now in modern browsers that implement ECMAScript 5 as @Alnitak mentions you could use Object.keys
, but in ES5 now we have the power of defining non-enumerable properties, these properties won't appear on the for-in
loop, if you need to detect them, you have to use an alternate method, for example, using the above function, or Object.keys
:
var obj = Object.create(null, { foo: { value: 1, /* enumerable:false... */} });
isEmpty(obj); // true
Object.keys(obj).length; // 0
// But the property exists:
obj.hasOwnProperty('foo'); // true
obj.foo; // 1
We need another approach if you want to catch non-enumerable own properties, that's why the Object.getOwnPropertyNames
method exist:
function isEmpty(obj) {
return Object.getOwnPropertyNames(obj).length == 0;
}
In ECMAScript 5 you can use:
if (Object.keys(a).length === 0) {
...
}
NB: this will only find enumerable properties.
精彩评论