简体   繁体   中英

Why javascript's alert shows strange values with arrays and objects?

I have a difficulty of understanding why alert shows me a strange things in the following expression.

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

Why "true" but not "undefined"?

Why "true" but not "undefined"?

Because ! is a boolean operator which always returns a boolean value. It would never produce the value undefined .

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

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

This is because the NOT operator ! will always return a boolean value , so if you were to examine your statements, you could break them down as follows :

{}[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

Going step by step:

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

The conversion is executed this way:

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

Logical not ! always transforms the argument to a boolean primitive type.
Check more about the falsy and logical not .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM