JS implements 5 methods for judging whether an object is an empty object (transfer)

Reposted from : JS implements 5 methods for judging whether an object is an empty object

1. Convert the json object into a json string, and then judge whether the string is "{}"

var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);//true

2. for in loop judgment

var obj = {};
var b = function() {
    for(var key in obj) {
        return false;
    }
    return true;
}
alert(b());//true

3.jquery's isEmptyObject method

This method is that jquery encapsulates the 2 methods (for in), and needs to rely on jquery when using it

var data = {};
var b = $.isEmptyObject(data);
alert(b);//true

4. Object.getOwnPropertyNames() method

This method is to use the getOwnPropertyNames method of the Object object to obtain the property names in the object, store them in an array, and return the array object. We can judge whether the object is empty by judging the length of the array Note: This method is not compatible with ie8
. Other browsers not tested

var data = {};
var arr = Object.getOwnPropertyNames(data);
alert(arr.length == 0);//true

5. Use ES6's Object.keys() method

Similar to method 4, it is a new method of ES6, and the return value is also an array of attribute names in the object

var data = {};
var arr = Object.keys(data);
alert(arr.length == 0);//true

So far, this article about the five methods of JS to determine whether an object is empty is introduced here. For more related content about JS judging whether an object is empty, please search the previous articles of scripthome or continue to browse the following related articles. Hope Everyone will support developpaer a lot in the future!

Articles you may be interested in: JavaScript A simple way to judge whether an object {} is an empty object Inventory of several methods Summary of several practical methods for JS to judge whether an object is an empty object

Reposted from : JS implements 5 methods for judging whether an object is an empty object

Guess you like

Origin blog.csdn.net/qq_41767116/article/details/129273570