2016-04-25 57 views
1

我很难理解为什么alert在下面的表达式中给我一个奇怪的东西。为什么javascript的alert会显示数组和对象的奇怪值?

alert(!+{}[0]); //it shows "true" 

为什么“真”而不是“未定义”?

+0

[为什么要警告(!!“0”)和警报(false ==“0”))在JavaScript中输出true的可能重复](http://stackoverflow.com/questions/4567393/why-do- alert0-and-alertfalse-0-both-output-true-in-javascript) – Boratzan

+1

因为它在js中有些问题:https://www.destroyallsoftware.com/talks/wat – Sugar

+0

你认为输出_should_是什么? – Andy

回答

0

一步一步走向:

{}[0] == undefined 
+undefined == NaN 
!NaN == true 
2

为什么 “真”,而不是 “未定义”?

因为!是一个布尔运算符,它总是返回一个布尔值。它永远不会产生值undefined

!false  // true 
!''  // true 
!null  // true 
!undefined // true 
!NaN  // true 
!0   // true 

相关:What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

+0

那么,它将我的所有表达式转换为“+”符号后的布尔值? – Alexey

+0

编号'!'带*任何*值并将其转换为布尔值。 '+'将任何值转换为*数字*。 –

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 
0

的转换这样执行:

  1. !+{}[0]{}[0] - >undefined
  2. !+undefined+undefined - >NaN
  3. !NaNNaN是falsy - >false
  4. !false
  5. true

逻辑非!总是变换一个布尔基元类型的参数。
查看更多关于falsylogical not

相关问题