Method: 1. Convert the object into a json string and determine whether the string is "{}"; 2. Use the "$.isEmptyObject(object)" statement; 3. Use "Object.getOwnPropertyNames( Object)" statement; 4. Use "Object.keys(Object)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript checks whether the object is empty
1. Convert the json object into a json string, and then determine whether the string is "{ }"
var data = {}; var b = (JSON.stringify(data) == "{}"); alert(b);//true
2. jquery's isEmptyObject method
This method encapsulates the 2 methods (for in) by jquery. You need to rely on jquery
var data = {}; var b = $.isEmptyObject(data); alert(b);//true
3. Object.getOwnPropertyNames() method
This method uses 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 the array by length to determine whether this object is empty
Note: This method is not compatible with ie8, and other browsers have not tested it
var data = {}; var arr = Object.getOwnPropertyNames(data); alert(arr.length == 0);//true
4. Use the Object.keys() method of ES6
Similar to method 3, it is a new method of ES6. The return value is also an array composed of property names in the object
var data = {}; var arr = Object.keys(data); alert(arr.length == 0);//true
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to check if an object is empty in Javascript. For more information, please follow other related articles on the PHP Chinese website!