我很难理解为什么alert在下面的表达式中给我一个奇怪的东西。为什么javascript的alert会显示数组和对象的奇怪值?
alert(!+{}[0]); //it shows "true"
为什么“真”而不是“未定义”?
我很难理解为什么alert在下面的表达式中给我一个奇怪的东西。为什么javascript的alert会显示数组和对象的奇怪值?
alert(!+{}[0]); //it shows "true"
为什么“真”而不是“未定义”?
一步一步走向:
{}[0] == undefined
+undefined == NaN
!NaN == true
为什么 “真”,而不是 “未定义”?
因为!
是一个布尔运算符,它总是返回一个布尔值。它永远不会产生值undefined
。
!false // true
!'' // true
!null // true
!undefined // true
!NaN // true
!0 // true
那么,它将我的所有表达式转换为“+”符号后的布尔值? – Alexey
编号'!'带*任何*值并将其转换为布尔值。 '+'将任何值转换为*数字*。 –
这是因为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
的转换这样执行:
!+{}[0]
({}[0]
- >undefined
)!+undefined
(+undefined
- >NaN
)!NaN
(NaN
是falsy - >false
)!false
true
逻辑非!
总是变换一个布尔基元类型的参数。
查看更多关于falsy和logical not。
[为什么要警告(!!“0”)和警报(false ==“0”))在JavaScript中输出true的可能重复](http://stackoverflow.com/questions/4567393/why-do- alert0-and-alertfalse-0-both-output-true-in-javascript) – Boratzan
因为它在js中有些问题:https://www.destroyallsoftware.com/talks/wat – Sugar
你认为输出_should_是什么? – Andy