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

我看到这件事的背景是,

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

当前回答

!! 不是运算符。这只是!操作员两次。

但使用JavaScript,应用!!在大多数情况下,将Object转换为Boolean是冗余和冗长的,因为:

值未定义或为空的任何对象,包括值为false的布尔对象,传递给有条件的陈述

示例:if({}){console.log(“{}是true”)}//logs:“{}是true”

其他回答

它将后缀转换为布尔值。

我认为值得一提的是,与逻辑“与/或”组合的条件不会返回布尔值,而是在&&的情况下返回最后一次成功或第一次失败,在条件链的||的情况下,返回第一次成功或最后一次失败。

res = (1 && 2); // res is 2
res = (true && alert) // res is function alert()
res = ('foo' || alert) // res is 'foo'

为了将条件转换为真正的布尔文字,我们可以使用双重否定:

res = !!(1 && 2); // res is true
res = !!(true && alert) // res is true
res = !!('foo' || alert) // res is true

在看到所有这些伟大的答案后,我想补充一个使用!!的理由!!。目前,我正在使用Angular 2-4(TypeScript),当我的用户未通过身份验证时,我希望将布尔值返回为false。如果他未通过身份验证,则令牌字符串将为null或“”。我可以通过使用下一段代码来实现这一点:

public isAuthenticated(): boolean {
   return !!this.getToken();
}

它模拟Boolean()转换函数的行为。无论给定什么操作数,第一个NOT都返回布尔值。第二个NOT否定该布尔值,从而给出变量的真正布尔值。最终结果与对值使用Boolean()函数相同。

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