寫在前面:通常在以下語句結構中需要判斷真假
1.if分支語句
2.while循環語句
3.for裏的第二個語句
一、JavaScript中有 6 種值爲“假”
1.false (布爾型)
2.null (用於定義空的或者不存在的引用)
3.undefined (未定義值)
4.0 (數值型)
5."'' (空字符串) (字符型)
6.NaN
這裏面 false 本身是布爾類型,其它 5 個則不是。除了這 6 個外,其它均爲“真” ,包括對象、數組、正則、函數等。注意 '0'、'null'、'false'、{}、[]也都是真值 。
二、雖然這六個值都爲“假”,它們之間並非都相等
console.log( false == null ) // false
console.log( false == undefined ) // false
console.log( false == 0 ) // true
console.log( false == '' ) // true
console.log( false == NaN ) // false
console.log( null == undefined ) // true
console.log( null == 0 ) // false
console.log( null == '' ) // false
console.log( null == NaN ) // false
console.log( undefined == 0) // false
console.log( undefined == '') // false
console.log( undefined == NaN) // false
console.log( 0 == '' ) // true
console.log( 0 == NaN ) // false
三、對於“==”,以上得出下列結論
1.false 除了和自身比較爲 true 外,和 0,"" 比較也爲 true
2.null 只和 undefined 比較時爲 true, 反過來 undefined 也僅和 null 比較爲 true,沒有第二個
3.0 除了和 false 比較爲 true,還有空字符串 ''" 和空數組 []比較也爲true
4.空字符串 '' 除了和 false 比較爲 true,還有一個數字 0