双感叹号? [英] Double exclamation points?
问题描述
可能重复:
什么是!! (不是)JavaScript中的运算符?
是什么!! JavaScript中的运算符(双惊叹号)是什么意思?
所以我正在调整一些代码并跑过这个:
So I was debuging some code and ran across this:
var foo.bar = 0; // this is actually passed from another function, adding it for context
function(foo) {
var someVar = !!foo.bar;
if (foo.bar) {
// ..stuff happens
} else {
// .. something else happens
}
}
好的我的问题是什么是 !!
?所有这一切都是使 0 === false
。
Okay my questions is what is the point of !!
? All that is doing is making the 0 === false
.
-
与
boolean(foo.bar)相比,使用它有什么好处
?
foo.bar可以按原样评估,因为 0 === false
已经,为什么要进行转换? (someVar不会在其他地方重复使用)
foo.bar can be evaluated in an if as is because 0 === false
already, so why go through the conversion? (someVar is not reused anywhere else)
推荐答案
这会将值转换为布尔值和确保布尔类型。
This converts a value to a boolean and ensures a boolean type.
"foo" // Evaluates to "foo".
!"foo" // Evaluates to false.
!!"foo" // Evaluates to true.
如果 foo.bar
通过,然后它可能不是0但是其他一些假值。请参阅以下真值表:
If foo.bar
is passed through, then it may not be 0 but some other falsy value. See the following truth table:
javascript的真实表
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
" \t\r\n" == 0 // true
来源:Doug Crockford
Source: Doug Crockford
当谈到NaN值时,Javascript也变得非常奇怪。这是我能想到的最好的情况!对于===会有不同的行为。
Javascript also gets really weird when it comes to NaN values. And this is the only case I can think of off the top of my head where !! would behave differently to ===.
NaN === NaN //false
!!NaN === !!NaN //true
// !!NaN is false
这篇关于双感叹号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!