javascript中2个感叹号的用法实例详解


在javascript代码中经常会见到!!的情况,本文即以实例形式较为深入的分析javascript中2个感叹号的用法。分享给大家供大家参考之用。具体分析如下:

javascript中的!!是逻辑"非非",即是在逻辑“非”的基础上再"非"一次。通过!或!!可以将很多类型转换成bool类型,再做其它判断。

一、应用场景:判断一个对象是否存在

假设有这样一个json对象:

{ color: "#E3E3E3", "font-weight": "bold" }

需要判断是否存在,用!!再好不过。

如果仅仅打印对象,无法判断是否存在:

var temp = { color: "#A60000", "font-weight": "bold" };
alert(temp);

结果:[object: Object]

如果对json对象实施!或!!,就可以判断该json对象是否存在:

var temp = { color: "#A60000", "font-weight": "bold" };
alert(!temp);

结果:false

var temp = { color: "#A60000", "font-weight": "bold" };
alert(!!temp);

结果:true

二、通过!或!!把各种类型转换成bool类型的惯例

1.对null的"非"返回true

var temp = null;
alert(temp); 

结果:null

var temp = null;
alert(!temp); 

结果:true

var temp = null;
alert(!!temp); 

结果:false

2.对undefined的"非"返回true

var temp;
alert(temp);

结果:undefined

var temp;
alert(!temp);

结果:true

var temp;
alert(!!temp);

结果:false

3.对空字符串的"非"返回true

var temp="";
alert(temp);

结果:空

var temp="";
alert(!temp);

结果:true

var temp="";
alert(!!temp);

结果:false

4.对非零整型的"非"返回false

var temp=1;
alert(temp);

结果:1

var temp=1;
alert(!temp);

结果:false

var temp=1;
alert(!!temp);

结果:true

5.对0的"非"返回true

var temp = 0;
alert(temp);

结果:0

var temp = 0;
alert(!temp);

结果:true

var temp = 0;
alert(!!temp);

结果:false

6.对字符串的"非"返回false

var temp="ab";
alert(temp);

结果:ab

var temp="ab";
alert(!temp);

结果:false

var temp="ab";
alert(!!temp);

结果:true

7.对数组的"非"返回false

var temp=[1,2];
alert(temp);

结果:1,2

var temp=[1,2];
alert(!temp);

结果:false

var temp=[1,2];
alert(!!temp);

结果:true

相信本文所述对大家的javascript程序设计的学习有一定的借鉴价值。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3