Summary of js methods for judging whether an object is an empty object
During the interview or development process, we often encounter such a question-how to judge whether an object is an empty object? Let us sum it up together!
Method 1: JSON.stringify() method
- Principle: convert the object into a string, and then judge whether it is equal to "{}"
let obj = {
};
console.log(JSON.stringify(obj) === "{}"); // true
Method 2: for in method
var obj = {
};
var fn = function () {
for (var key in obj) {
return false; // 若不为空,可遍历,返回false
}
return true;
};
console.log(fn()); // true
Method 3: Object.keys() method
- Principle: Object.keys() method returns an array of object property names. If the length is 0, it is an empty object (ES6 writing method)
let obj = {
};
let arr = Object.keys(obj);
console.log(arr.length == 0); // true
Method 4: Object.getOwnPropertyNames() method
- Principle: The Object.getOwnPropertyNames() method obtains the property names of the object and stores them in an array. If the length is 0, it is an empty object.
var obj = {
};
var arr = Object.getOwnPropertyNames(obj);
console.log(arr.length == 0); // true
Method 5: jQuery's isEmptyObject() method
- Principle: Use the for in method to judge (note: remember to quote jquery when using this method).
var obj = {
};
var b = $.isEmptyObject(obj);
console.log(b); // true