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

我看到这件事的背景是,

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

当前回答

这个构造是将任何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!

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

! 表示不。所以真是假的,而且!假是真!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);

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

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

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

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

有时,有必要检查函数中是否有值,数量本身对我们来说并不重要,但它是否重要。

例如,我们想检查用户是否有专业,并且我们有一个如下的功能:

hasMajor() {return this.major} // It returns "(users major is) Science"

但答案对我们来说并不重要。我们只想检查它是否有主,我们需要一个布尔值(true或false)。我们如何得到它?

就像这样:

hasMajor() { return !(!this.major)}

或相同

hasMajor() {return !!this.major)}

如果this.major有值,那么!this.major返回false,但因为值有出口,我们需要返回true,所以我们使用!两次返回正确答案!(!this.major)。

只是为了检查是否存在

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