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

我看到这件事的背景是,

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

当前回答

要将JavaScript变量转换为布尔值,

var firstname = "test";
// Type of firstname is string

var firstNameNotEmpty = !!firstname;
// Type of firstNameNotEmpty is Boolean

JavaScript false表示“”、0、undefined和null。

JavaScript对于除零以外的数字是真的,而不是空字符串、{}、[]和new Date(),因此,

!!("test") /* Is true */
!!("") /* Is false */

其他回答

这是我找到的最简单的答案:它的工作方式相当于布尔值。

这是一种非常晦涩的类型转换方法。

! 表示不。所以真是假的,而且!假是真!0为真,并且!1为假。

所以你要将一个值转换成布尔值,将其反转,然后再次反转。

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

// Or just
val.enabled = Boolean(userId);

注意:由于!=运算符的作用以及哪些值被认为是正确的。

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

true === !!10

false === !!0

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

这里有很多很棒的答案,但如果你读到这里,这帮助我“找到答案”。在Chrome(等)中打开控制台,然后开始键入:

!(!(1))
!(!(0))
!(!('truthy')) 
!(!(null))
!(!(''))
!(!(undefined))
!(!(new Object())
!(!({}))
woo = 'hoo'
!(!(woo))
...etc., etc., until the light goes on ;)

当然,这些都和仅仅打字一样!!但添加的括号可能有助于使其更易于理解。