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

我看到这件事的背景是,

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 */

其他回答

这是检查未定义、“未定义”、null、“null”、“”

if (!!var1 && !!var2 && !!var3 && !!var4 ){
   //... some code here
}

你可以考虑!!以这种方式:

当第一次!应用时,变量变为布尔值,但值相反然后,第二个!只是恢复正义,并将价值恢复到原来的同等价值

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

!!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!

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

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