Home > Article > Web Front-end > How to determine whether an object is empty in javascript
Method: 1. Use the "JSON.stringify()" method to convert the object into a json string, and then determine whether the string is "{}"; 2. Use "Object.keys(object name) ).length==0" determines whether the length is 0, and then determines whether the object is empty.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
1. Determine through the JSON.stringify() method
Convert the object into a json string, and then determine whether the string is " {}" will do.
var obj = {}; var objStr = JSON.stringify(obj); if(objStr === '{}') { console.log("对象为空"); }else { console.log("对象不为空"); }
Note: Why toString()
is not used here is because it returns Object
.
2. Use the es6 method Object.keys() length property for judgment
var obj = {}; var arr = Object.keys(obj); if (arr.length == 0){ console.log("对象为空"); }else { console.log("对象不为空"); }
Object.keys
method is used for traversal in JavaScript A method of an object's properties. The parameter it passes in is an object, and what it returns is an array. The array contains all the property names of the object.
You can use the length attribute to determine whether this array is empty, and then determine whether the object is empty.
[Recommended learning: javascript video tutorial]
The above is the detailed content of How to determine whether an object is empty in javascript. For more information, please follow other related articles on the PHP Chinese website!