Recently, the project encountered a problem in judging empty objects. Please review the relevant information and summarize it.
Judging an empty object is no longer the same as judging an empty string, because an empty object is also an object, and memory needs to be allocated separately, rather than being empty like a string, it is a big pot of rice. Everyone is equal, as follows:
As shown in the above code, it can be found that whether it is an empty object created through the object literal or an empty object created through the Object constructor, it is not equal to each other.
1. Convert object to string for comparison
This method is not recommended, but it is indeed the easiest to think of. It mainly uses JSON.stringify() to force the object. It is posted for a look:
var a={}; var b=new Object(); console.log("Comparison result of object literals: "+(JSON.stringify(a)=="{}")) console.log("Comparison result of constructor: "+(JSON.stringify(b)=="{}"))We can get that the comparison between two empty objects converted to strings is true, which can solve this problem, but it is not recommended. Let’s talk about the second method below.
2.for in loop
Use a for in loop to iterate through all attributes to determine whether the object is an empty object:
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")}Use the for in loop to loop the object when looping, and the corresponding looping subscript when looping the array, such as:
var b = ["hello","my","world"]for(var index in b){ console.log(b[index]);}//hello my worldThe above is all the content (title) brought to you by the editor. I hope you will support Wulin.com more~