For example: when we make a shopping cart in an e-commerce project, when there are products in the shopping cart, it is a page, but when we empty the shopping cart, the page displays another page, for example: shopping is an empty page. At this point, we need to judge whether the object of commodity is empty.
For example: when judging whether an object is empty, it is not allowed to directly use obj == {}.
The following are 5 common ways to judge whether an object is empty:
- JSON.stringify converts the object into a string form, and then judges whether it is equal to '{}'
let obj = {};
console.log(JSON.stringify(obj) == '{}');
2. Use the object.keys() method in ES6 to return an array containing all property names of the object, and then check whether the length of the array is 0.
let obj = {};
console.log(Object.keys(obj).length == 0);
3. Use the for in loop to traverse the property names of the object. Returns false if not empty, true if empty
var obj = {};
var aaa= function(obj){
for(let key in obj){
return false;
}
return true;
}
console.log(aaa(obj));
4. Use Object.getOwnPropertyNames() to get the object property name, save it in the array, and then judge whether the length of the array is 0
var obj = {};
console.log(Object.getOwnPropertyNames(obj) == 0);
5.5. Use the isEmptyObject method in jq
var obj = {};
console.log($.isEmptyObject(obj));