javascript中判断对象是否为空几种场景

1. 代码1:
var a = {};
if(!a){ console.log(1);}
else if(a == null) { console.log(2);} 
else { console.log(3);}

结果为:3  // var a = {} 不是空对象

 

2. 代码2:
var b = {};
if(b == {}){ console.log(4);}
if(b == '{}') { console.log(5);}
if(typeof(b) == 'object') { console.log(6);}
结果为:6 // var a = {} 要使用typeof 判断类型,且是 object;不能直接和字符串双等于比较

posted @ 2022-01-07 18:07  特朗鸟  阅读(41)  评论(0)    收藏  举报