js 中两个感叹号的作用

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

 常见例子,空字符串的非是true

console.log(
  !true,         //false
  !false,        //true
  !0,            //true
  !'',           //true
  ![],           //false
  !null,         //true
  !undefined,    //true
  !{},           //false
)

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

假设有这样一个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

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1795892