js 判断 json 对象是否为空

2020-05-19  

1、转换为字符串比较

var obj1 = {}; 
var obj2 = new Object(); 
console.log(JSON.stringify(obj1) == '{}'); //true
console.log(JSON.stringify(obj2) == '{}'); //true 


2、通过遍历判断对象是否存在属性

var obj1 = {}; 
var obj2 = new Object(); 

function isEmptyObject(obj){  
    for(var key in obj){  
        return false;
    };  
    return true;
};
console.log(isEmptyObject(obj1)); //true
console.log(isEmptyObject(obj2)); //true
console.log(isEmptyObject(null)); //true

 

3、jquery isEmptyObject

var obj1 = {}; 
var obj2 = new Object(); 
console.log($.isEmptyObject(obj1)); //true
console.log($.isEmptyObject(obj2)); //true
console.log($.isEmptyObject(undefined)); //true

 

ConstXiong 备案号:苏ICP备16009629号-3