- 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
- for in loop judgment
var obj = {
};
var b = function() {
for(var key in obj) {
return false;
}
return true;
}
alert(b());
//true
- 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
- Object.getOwnPropertyNames()
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
var data = {
};
var arr = Object.getOwnPropertyNames(data);
alert(arr.length == 0);
//true
- 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