为什么javascript的警报会显示数组和对象的奇怪值?

时间:2016-04-25 13:35:02

标签: javascript arrays object expression alert

我很难理解为什么警报会在下面的表达式中向我显示一些奇怪的东西。

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

为什么" true"但不是"未定义"?

4 个答案:

答案 0 :(得分: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?

答案 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)

转换以这种方式执行:

  1. !+{}[0]{}[0] - > undefined
  2. !+undefined+undefined - > NaN
  3. !NaNNaN是假的 - > false
  4. !false
  5. true
  6. Logical not !总是将参数转换为布尔基元类型 详细了解falsylogical not