我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
!!x是布尔(x)的简写。
第一次爆炸迫使JavaScript引擎运行Boolean(x),但它也有反转值的副作用。所以第二次爆炸消除了副作用。
其他回答
这个构造是将任何JavaScript表达式转换为它的布尔等价物。
例如:!!“他击落了我”==真的!!0===假。
!!expr(后跟表达式的两个!运算符)根据表达式的真实性返回布尔值(true或false)。当用于非布尔类型时,它更有意义。考虑以下示例,尤其是第三个示例及其后续示例:
!!false === false
!!true === true
!!0 === false
!!parseInt("foo") === false // NaN is falsy
!!1 === true
!!-1 === true // -1 is truthy
!!(1/0) === true // Infinity 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 value is falsy
!!undefined === false // undefined primitive is falsy
!!null === false // null is falsy
!!{} === true // an (empty) object is truthy
!![] === true // an (empty) array is truthy; PHP programmers beware!
它将Object转换为布尔值。如果为假(例如,0、null、undefined等),则为假,否则为真。
!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
我只是想补充一下
if(variableThing){
// do something
}
与
if(!!variableThing){
// do something
}
但当某些东西未定义时,这可能是一个问题。
// a === undefined, b is an empty object (eg. b.asdf === undefined)
var a, b = {};
// Both of these give error a.foo is not defined etc.
// you'd see the same behavior for !!a.foo and !!b.foo.bar
a.foo
b.foo.bar
// This works -- these return undefined
a && a.foo
b.foo && b.foo.bar
b && b.foo && b.foo.bar
这里的技巧是,&&s链将返回它找到的第一个假值,这可以被馈送到if语句等。因此,如果b.foo未定义,它将返回undefined并跳过b.foo.bar语句,我们不会得到任何错误。
上面的返回未定义,但如果您有一个空字符串,false,null,0,undefined,这些值将返回,一旦我们在链中遇到它们——[]和{}都是“truthy”,我们将沿着所谓的“&&链”继续到右边的下一个值。
P.S.执行上述(b&&b.foo)的另一种方法是(b||{}).foo。这些方法是等效的,因为如果b未定义,则b||{}将为{},并且您将访问空对象中的值(无错误),而不是尝试访问“undefined”中的值。
因此,(b||{}).foo与b&&b.foo相同,((b||{})/foo||{}).bar与b&&b.foo&&b.foo.bar相同。
它不是一个操作员;它是两个。它相当于以下内容,是将值转换为布尔值的快速方法。
val.enabled = !(!enable);