Recently, the project encountered a problem of judging empty objects, consult the relevant data and then summarize.
It is not better to judge an empty object than to judge an empty string, because an empty object is also an object that needs to be allocated separately, rather than a large pot of rice like a string, and everyone is equal, the following code:
As you can see in the code, an empty object created by an object literal or an empty object created by the object constructor is not equal to each other.
1. Convert objects to strings for comparison
This method is not recommended, but it is indeed the most easy to think of, the main use of json.stringify () This method to the object for a strong turn, posted out for a look only:
var a={};
var b=new Object ();
Console.log ("Comparison of object literals:" + (json.stringify (a) = = "{}")
Console.log ("Comparison of Constructors:" + (json.stringify (b) = = "{}")
We can get two null objects converted to string after the comparison is true, can solve this problem, but not recommended, the second method.
2.for in loop
The For In loop allows you to iterate through all the properties to determine whether an object is an empty object at a time:
var a={};
var b=new Object ();
function Isemptyobject (obj) {for
[var key in obj] {return
false
};
return True
};
if (Isemptyobject (a)) {
alert ("A is an empty object")
}
if (Isemptyobject (b)) {
alert ("B is an empty object")
}
Loops the property when the object is cycled using a for in loop, and the corresponding array loops with the subscript, such as:
var b = [' Hello ', ' my ', ' World ' for '
(var index in b) {
console.log (B[index]);
}
Hello my World
The above is a small series for everyone to bring the (title) all the content, I hope that we support the cloud-Habitat Community ~