我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?

我看到这件事的背景是,

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

当前回答

只是为了检查是否存在

if(!!isComplianceOnHold){
//write code here is not undefined
//if isComplianceOnHold is undefined or null will not enter in net is false
// if isComplianceOnHold is not null or even boolean net result is true and enter inside if block
}

任何值未定义或为null的对象,包括值为false的布尔对象,在传递给条件语句时其计算结果为true

其他回答

const foo=“bar”;console.log(!!foo);//布尔值:真

! 对值求反(反转),并始终返回/生成布尔值。所以!”bar'将产生false(因为'bar'是truthy=>否定+布尔值=false)。附加的!运算符,该值再次被求反,因此false变为true。

它不是一个操作员;它是两个。它相当于以下内容,是将值转换为布尔值的快速方法。

val.enabled = !(!enable);

以下是AngularJS的一段代码:

var requestAnimationFrame = $window.requestAnimationFrame ||
                            $window.webkitRequestAnimationFrame ||
                            $window.mozRequestAnimationFrame;

var rafSupported = !!requestAnimationFrame;

他们的意图是根据requestAnimationFrame中函数的可用性将rafSupported设置为true或false。

通常可以通过以下方式进行检查:

if(typeof requestAnimationFrame === 'function')
    rafSupported =true;
else
    rafSupported =false;

这条短路可以用!!

rafSupported = !!requestAnimationFrame;

因此,如果requestAnimationFrame被分配了一个函数,那么!requestAnimationFrame将为false,还有一个!这是真的。

如果requestAnimationFrame未定义,则!requestAnimationFrame将是真的,还有一个!这将是错误的。

它将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

JavaScript中的一些运算符执行隐式类型转换,有时用于类型转换。

一元!运算符将其操作数转换为布尔值并对其求反。

这一事实导致了以下习惯用法,您可以在源代码中看到:

!!x // Same as Boolean(x). Note double exclamation mark