我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
看来是!!运算符导致双重否定。
var foo = "Hello, World!";
!foo // Result: false
!!foo // Result: true
其他回答
它将后缀转换为布尔值。
这是一次双重手术。第一个!将值转换为布尔值并反转其逻辑值。第二个!反转逻辑值。
这里有很多很棒的答案,但如果你读到这里,这帮助我“找到答案”。在Chrome(等)中打开控制台,然后开始键入:
!(!(1))
!(!(0))
!(!('truthy'))
!(!(null))
!(!(''))
!(!(undefined))
!(!(new Object())
!(!({}))
woo = 'hoo'
!(!(woo))
...etc., etc., until the light goes on ;)
当然,这些都和仅仅打字一样!!但添加的括号可能有助于使其更易于理解。
它返回变量的布尔值。
相反,可以使用布尔类。
(请阅读代码说明。)
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
!!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!