JS judges whether the object is an empty object {}

A subtotal of a knowledge point, sometimes we want to judge whether an object is an empty object, that is, an object {} without any attributes,
what? you want to use

obj == null

? ,
stop messing around, obviously I didn't mean that.

What? Do you want to use this again?

obj == {
    
    }

Forget it, let me show you a piece of code:

let obj={
    
    };
return obj == {
    
    }

Does this code return true? Sharp-eyed students should be able to see it at a glance, don't look at the two pairs of curly braces that look exactly the same, but they will definitely return false. Why, let me explain in detail:
In JavaScript, when you create an empty object let obj = {}, and then Returns false when comparing this object to another empty object {}. This is because in JavaScript, objects are compared based on reference, not content.
Two different objects are considered unequal even if they have the same content, because they have different reference addresses in memory.

In fact, this line of code will not be true under any circumstances, so how can I judge whether this object is an empty object? There are the following methods:
Method 1 (recommended), to verify whether an object is an empty object, you can use Object.keys(obj) to check whether it has any properties.

let obj = {
    
    };
let isEmpty = Object.keys(obj).length === 0;
console.log(isEmpty); // true

Method 2 (not recommended), you can also use JSON.stringify(obj) to convert the object into a string, and then check whether the string is "{}" to determine whether the object is an empty object. Note, however, that this approach may not work for objects containing functions or circular references.

let obj = {
    
    };
let isEmpty = JSON.stringify(obj) === "{}";
console.log(isEmpty); // true

Don't read it, save it quickly, I won't delete the article, don't worry.

Guess you like

Origin blog.csdn.net/Spy003/article/details/132014152