我很难理解为什么警报会在下面的表达式中向我显示一些奇怪的东西。
alert(!+{}[0]); //it shows "true"
为什么" true"但不是"未定义"?
答案 0 :(得分:2)
为什么“真实”而不是“未定义”?
因为!
是一个布尔运算符,它总是返回一个布尔值。它永远不会产生值undefined
。
!false // true
!'' // true
!null // true
!undefined // true
!NaN // true
!0 // true
答案 1 :(得分:1)
这是因为NOT operator !
will always return a boolean value,所以如果你要检查你的陈述,你可以按如下方式分解它们:
{}[0] // yields undefined
+(undefined) // assumes arithemetic, but doesn't know how to handle it so NaN
!(NaN) // Since a boolean must be returned and something is there, return true
答案 2 :(得分:0)
一步一步走:
{}[0] == undefined
+undefined == NaN
!NaN == true
答案 3 :(得分:0)
转换以这种方式执行:
!+{}[0]
({}[0]
- > undefined
)!+undefined
(+undefined
- > NaN
)!NaN
(NaN
是假的 - > false
)!false
true
Logical not !
总是将参数转换为布尔基元类型
详细了解falsy和logical not。