js中!!写法其实是将oObject强制转换为布尔值。 如果它是假的(例如0,null,undefined等),则为false,否则为true。
前言
俺刚看到的时候也是一脸懵逼,这tm是什么鬼。
!oObject !!oObject
因此!!不是运算符,它只是使用了两次!运算符。
真实案例
真实案例中常见的一个方法就是用来检测IE版本,请看以下代码:
let isIE8 = false; isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);//是否为IE8.0 console.log(isIE8); // returns true or false
如果直接打印以下结果,将会输出Araay或null
console.log(navigator.userAgent.match(/MSIE 8.0/)); // 返回Array或null
如果使用!!,将会输出true或false
console.log(!!navigator.userAgent.match(/MSIE 8.0/)); //输出true或false
总结
我们可以用以下代码来表示
!!true = true 并且 !true= false