1. 代码1:
var a = {};
if(!a){ console.log(1);}
else if(a == null) { console.log(2);}
else { console.log(3);}
var b = {};
if(b == {}){ console.log(4);}
if(b == '{}') { console.log(5);}
if(typeof(b) == 'object') { console.log(6);}
var c = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}
结果为:7
所以可以使用代码3的方法判断对象是否为空对象{};SON.stringify可以将对象转化为字符串
var d = {};
var e = {id:1};
if(d.id){ console.log(8);}
if(e.id){ console.log(9);}
var a = {};
if(!a){ console.log(1);}
else if(a == null) { console.log(2);}
else { console.log(3);}
结果为:3 // var a = {} 不是空对象
var b = {};
if(b == {}){ console.log(4);}
if(b == '{}') { console.log(5);}
if(typeof(b) == 'object') { console.log(6);}
结果为:6 // var a = {} 要使用typeof 判断类型,且是 object;不能直接和字符串双等于比较
var c = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}
结果为:7
所以可以使用代码3的方法判断对象是否为空对象{};SON.stringify可以将对象转化为字符串
var d = {};
var e = {id:1};
if(d.id){ console.log(8);}
if(e.id){ console.log(9);}
结果为:9
本文介绍了几种在JavaScript中判断对象是否为空的有效方法。通过不同代码示例,对比了使用typeof、JSON.stringify及直接属性访问等手段的区别,并分析了各自的优劣。
1170

被折叠的 条评论
为什么被折叠?



