我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,如下所示:!!
。有人可以告诉我这个运算符(operator)是做什么的吗?
我看到这个的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
最佳答案
它将Object
转换为boolean
。如果它是假的(例如,0
、null
、undefined
等),那么它将是false
,否则,true
。
!object // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation
所以 !!
不是一个运算符;只是两次 !
运算符。
这样做可能更简单:
Boolean(object) // Boolean
真实示例“测试 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
关于javascript - 是什么 !! JavaScript 中的(不是 not)运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25053504/