小编典典

JavaScript中的(不是)操作符?

javascript

我看到了一些代码,它们似乎使用了我不认识的运算符,它们以两个感叹号的形式出现,如下所示:!!。有人可以告诉我这个操作员做什么吗?

我看到的背景是

this.vertical = vertical !== undefined ? !!vertical : this.vertical;

阅读 418

收藏
2020-04-22

共1个答案

小编典典

转换Objectboolean。如果是falsey(例如0nullundefined等),这将是false,否则,true

!oObject  // inverted boolean
!!oObject // non inverted boolean so true boolean representation

因此!!,不是运算符,只是!运算符的两倍。

实际示例“测试IE版本”:

const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8); // returns true or false

如果你⇒

console.log(navigator.userAgent.match(/MSIE 8.0/));  
// returns either an Array or null

但是如果你⇒

console.log(!!navigator.userAgent.match(/MSIE 8.0/));  
// returns either true or false
2020-04-22