
我在做项目时遇到一个问题,判断一个对象是否为空,发现可以做这个判断,代码:
1. 代码1:
var a = {};
if(!a){ console.log(1);}
else if(a == null) { console.log(2);}
else { console.log(3);}

结果是: 3
2. 代码2:
var b = {};
if(b == {}){ console.log(4);}
if(b == '{}') { console.log(5);}
if(typeof(b) == 'object') { console.log(6);}

结果是: 6
3. 代码3:
var c = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}

var c = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}
结果是: 7
因此您可以使用代码3的方法确定对象是否为空{};

如果对象不为空,并且您知道该对象也不为空,则必须存在某个属性(例如{id: 111}),您可以像这样判断它:
4. 代码4:
var d = {};
var e = {id:111};
if(d.id){ console.log(8);}
if(e.id){ console.log(9);}
结果是: 9
摘要: 显然,代码3的判断方法相对“强”js判断对象为空js判断对象为空,但效率显然不如代码4的判断方法
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-264687-1.html
事物的本质要用心灵才能看见