我看到一些代码似乎使用了一个我不认识的运算符,以两个感叹号的形式出现,如下所示: !! 。有人可以告诉我这个运营商做了什么?
我看到这个的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
将 oObject oObject为布尔值。如果它是假的(例如 0, null , undefined等),则为false ,否则为true 。
!oObject //Inverted boolean
!!oObject //Non inverted boolean so true boolean representation所以!!不是运营商,只是!操作员两次。
真实世界示例 “测试 IE 版本”:
let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false如果你⇒
console.log(navigator.userAgent.match(/MSIE 8.0/));
// returns null但如果你⇒
console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// returns true or false
这是进行类型转换的一种非常模糊的方式。
! 不是 。所以!true是false ,而且!false是true 。 !0为true , !1为false 。
所以你要将一个值转换为布尔值,然后将其反转,然后再将其反转。
// Maximum Obscurity:
val.enabled = !!userId;
// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;
// And finally, much easier to understand:
val.enabled = (userId != 0);
!!expr根据表达式的真实性返回一个布尔值( true或false )。在非布尔类型上使用时更有意义。考虑这些示例,尤其是第 3 个示例及以后的示例:
!!false === false
!!true === true
!!0 === false
!!parseInt("foo") === false // NaN is falsy
!!1 === true
!!-1 === true // -1 is truthy
!!"" === false // empty string is falsy
!!"foo" === true // non-empty string is truthy
!!"false" === true // ...even if it contains a falsy value
!!window.foo === false // undefined is falsy
!!null === false // null is falsy
!!{} === true // an (empty) object is truthy
!![] === true // an (empty) array is truthy; PHP programmers beware!