Probably a duplicate of this question.
Silly javascript question: I want to check if an object is the emtpy object.
I call empty object the object that results from using the empty object literal, as in:
var o = {};
As expected, neither ==
nor ===
work, as the two following statements
alert({}=={});
alert({}==={});
give false.
Examples of expressions that do not evaluate to the empty object:
0
""
{a:"b"}
[]
new function(){}
So what is the shortest way to evaluate for the empty 开发者_高级运维object?
You can also use Object.keys() to test if an object is "empty":
if (Object.keys(obj).length === 0) {
// "empty" object
} else {
// not empty
}
function isEmpty(o){
for(var i in o){
if(o.hasOwnProperty(i)){
return false;
}
}
return true;
}
You can use this syntax
if (a.toSource() === "({})")
but this doesn't work in IE. As an alternative to the "toSource()" method encode to JSON of the ajax libraries can be used:
For example,
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
jquery + jquery.json
There is not really a short way to determine if an object is empty has Javascript creates an object and internally adds constructor
and prototype
properties of Object automatically.
You can create your own isEmpty()
method like this:
var obj={}
Object.prototype.isEmpty = function() {
for (var prop in this) {
if (this.hasOwnProperty(prop)) return false;
}
return true;
};
alert(obj.isEmpty());
So, if any object has any property, then the object is not empty else return true.
javascript:
cs = 'MTobj={ }; JSON.stringify(MTobj)=="{}"';
alert(cs+' is '+eval(cs));
cs = 'MTnot={a:2}; JSON.stringify(MTnot)=="{}"';
alert(cs+' is '+eval(cs));
says
MTobj={ }; JSON.stringify(MTobj)=="{}" is true
MTnot={a:2}; JSON.stringify(MTnot)=="{}" is false
Caveat! Beware! there can be false positives!
javascript:
cs = 'MTobj={ f:function(){} }; JSON.stringify(MTobj)=="{}"';
alert(cs+' is '+eval(cs));
alert("The answer is wrong!!\n\n"+
(cs="JSON.stringify({ f:function(){} })")+
"\n\n returns\n\n"+eval(cs));
精彩评论