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

我看到这件事的背景是,

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

当前回答

!!foo两次应用一元not运算符,并用于转换为布尔类型,类似于使用一元加号+foo转换为数字,并连接空字符串“”+foo以转换为字符串。

除了这些黑客,您还可以使用与基元类型相对应的构造函数(不使用new)来显式转换值,即。,

Boolean(foo) === !!foo
Number(foo)  === +foo
String(foo)  === ''+foo

其他回答

只是为了检查是否存在

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

它返回变量的布尔值。

相反,可以使用布尔类。

(请阅读代码说明。)

var X = "test"; // The X value is "test" as a String value
var booleanX = !!X // booleanX is `true` as a Boolean value because non-empty strings evaluates as `true` in Boolean
var whatIsXValueInBoolean = Boolean(X) // whatIsXValueInBoolean is `true` again
console.log(Boolean(X) === !!X) // Writes `true`

即,布尔(X)=!!X正在使用。

请检查下面的代码片段↓

设a=0console.log(“a:”,a)//以其类型写入值console.log(“!a:”,!a)//将“0在布尔值中不为真”写入为布尔值-因此为真。在布尔值中,0表示假,1表示真。console.log(“!!a:”,!!a)//以布尔形式写入0值。0表示错误。console.log(“Boolean(a):”,Boolean(b))//等于`!!一个`console.log(“\n”)//换行a=1console.log(“a:”,a)console.log(“!a:”,!a)console.log(“!!a:”,!!a)//以布尔形式写入1个值console.log(“\n”)//换行a=“”console.log(“a:”,a)console.log(“!a:”,!a)//将“”在布尔值中不为真,因此为真。在布尔值中,空字符串、空值和未定义值表示false,如果有字符串则表示true。console.log(“!!a:”,!!a)//将“”值写入布尔值console.log(“\n”)//换行a=“测试”console.log(“a:”,a)//以其类型写入值console.log(“!a:”,!a)console.log(“!!a:”,!!a)//以布尔形式写入“测试”值console.log(“布尔值(a)==!!a:”,布尔(a)===!!a) //写入true

看来是!!运算符导致双重否定。

var foo = "Hello, World!";

!foo // Result: false
!!foo // Result: true

这只是逻辑NOT运算符,两次。它用于将某些内容转换为布尔值,例如:

true === !!10

false === !!0

以下是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将是真的,还有一个!这将是错误的。