How to verify that this logical hash is empty in javascript?

Possible duplicates:
Comparing Objects in JavaScript
How to check an empty Javascript object from JSON?

var abc = {}; console.log(abc=={}) //false, why? 

Why is this a lie? How can I map an empty hash map ...?

+4
source share
4 answers

{} is a new instance of the object. So abc! == "new object" because abc is a different 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; } alert("abc is empty? "+ isEmpty(abc)) alert("abcd is empty? "+ isEmpty(abcd)) 

Update: now we saw some others offer the same thing, but using hasOwnProperty

I could not check the difference in IE8 and Fx4 between mine and them, but I would like to be enlightened.

+1
source
 if (abc.toSource() === "({})") // then `a` is empty 

OR

 function isEmpty(abc) { for(var prop in abc) { if(abc.hasOwnProperty(prop)) return false; } return true; } 
+1
source
 var abc = {}; 

create object

so you can try type:

 if (typeof abc == "object")... 
0
source

Operator var abc = {}; creates a new (empty) object and points to the variable abc at this object.

The abc == {} test creates a second new (empty) object and checks if abc points to the same object. That it is not, therefore, false .

There is no built-in method (which I know) to determine if an object is empty, but you can write your own short function to do this as follows:

 function isObjectEmpty(ob) { for (var prop in ob) if (ob.hasOwnProperty(prop)) return false; return true; } 

(Checking hasOwnProperty() - ignore properties in the prototype chain not directly in the object.)

Note: the term “object” is what you want to use, not a “hash map”.

0
source

All Articles