js 判断对象是否为空,没有属性

来源:互联网 发布:手机版淘宝上评价管理 编辑:程序博客网 时间:2024/05/20 17:42

. 代码1:

?
1
2
3
4
vara = {};
if(!a){ console.log(1);}
elseif(a == null) { console.log(2);}
else{ console.log(3);}

结果为:3

2. 代码2:

?
1
2
3
4
varb = {};
if(b == {}){ console.log(4);}
if(b == '{}') { console.log(5);}
if(typeof(b) == 'object') { console.log(6);}

结果为:6

3. 代码3:

?
1
2
varc = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}
?
1
2
varc = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}

结果为:7

所以可以使用代码3的方法判断对象是否为空对象{};

如果对象不为空,并且知道对象不为空时,某个属性(比如{id:111})一定存在,则可以里这样判断:

4. 代码4:

?
1
2
3
4
vard = {};
vare = {id:111};
if(d.id){ console.log(8);}
if(e.id){ console.log(9);}

结果为:9

小结:显然代码3的判断方式比较“强势”,但效率明显不如代码4的判断方法

以上就是小编为大家带来的JavaScript 判断一个对象{}是否为空对象的简单方法全部内容了,希望大家多多支持脚本之家~

阅读全文
0 0
原创粉丝点击