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

我看到这件事的背景是,

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

当前回答

它返回变量的布尔值。

相反,可以使用布尔类。

(请阅读代码说明。)

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

其他回答

JavaScript中的一些运算符执行隐式类型转换,有时用于类型转换。

一元!运算符将其操作数转换为布尔值并对其求反。

这一事实导致了以下习惯用法,您可以在源代码中看到:

!!x // Same as Boolean(x). Note double exclamation mark

!! 只是两次NOT运算符。净效果就是转换任何东西以确保布尔数据类型。例如

!!undefined为false!!0为假!!null为false!!anyobject为true!!真是真!!false是false!0为真!1为假!!'' 是假的

它将后缀转换为布尔值。

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

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