How do I check this boolean hashmap is empty in javascript? [duplicate]
Possible Duplicates:
Object comparison in JavaScript How do I test for an empty Javascript object from JSON?
var abc 开发者_开发技巧= {};
console.log(abc=={}) //false, why?
Why is it false? How do I match a blank hash map...?
{} is a new object instantiation. So abc !== "a new object" because abc is another object.
This test works:
var abc = {};
var abcd = {
"no": "I am not empty"
}
function isEmpty(obj) {
for (var o in obj)
if (o) return false;
return true;
}
console.log("abc is empty? " + isEmpty(abc))
console.log("abcd is empty? " + isEmpty(abcd))
Update: Just now saw that several others suggested the same, but using hasOwnProperty
I could not verify a difference in IE8 and Fx4 between mine and theirs but would love to be enlightened
if (abc.toSource() === "({})") // then `a` is empty
OR
function isEmpty(abc) {
for(var prop in abc) {
if(abc.hasOwnProperty(prop))
return false;
}
return true;
}
var abc = {};
this create an object
so you can try the type of:
if (typeof abc == "object")...
The statement var abc = {};
creates a new (empty) object and points the variable abc
to that object.
The test abc == {}
creates a second new (empty) object and checks whether abc
points to the same object. Which it doesn't, hence the false
.
There is no built-in method (that I know of) to determine whether an object is empty, but you can write your own short function to do it like this:
function isObjectEmpty(ob) {
for (var prop in ob)
if (ob.hasOwnProperty(prop))
return false;
return true;
}
(The hasOwnProperty()
check is to ignore properties in the prototype chain not directly in the object.)
Note: the term 'object' is what you want to use, not 'hash map'.
精彩评论