This converts a value to a boolean and ensures a boolean type .(这会将值转换为布尔值并确保布尔类型 。)
"foo" // Evaluates to "foo".
!"foo" // Evaluates to false.
!!"foo" // Evaluates to true.
If foo.bar
is passed through, then it may not be 0 but some other falsy value.(如果foo.bar
被传递,那么它可能不是0而是一些其他的虚假值。) See the following truth table:(请参阅以下真值表:)
Truth Table for javascript(javascript的真值表)
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
"
" == 0 // true
Source: Doug Crockford(资料来源:Doug Crockford)
Javascript also gets really weird when it comes to NaN values.(当谈到NaN值时,Javascript也变得非常奇怪。) 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…