我很難理解爲什麼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