Comparisons
>、<、>=、<=、==、!=、===、!==
Boolean is the result
如同其他運算符號,比較運算符號返回一個值,這值為布林值。
alert( 2 > 1 ); // true (correct)
alert( 2 == 1 ); // false (wrong)
let result = 5 > 4; // assign the result of the comparison
alert( result ); // true
String comparison
比較 2 個字串的規則:用 Unicode 由左到右比較字母大小,大小寫式有分別,小寫比較大。
Comparison of different types
比較不同類型,會把值轉換成數字。
alert( '2' > 1 ); // true, string '2' becomes a number 2
alert( '01' == 1 ); // true, string '01' becomes a number 1
Strict equality
==
、!=
有問題,會把類型轉換。
alert( 0 == false ); // true
===
、!==
不會有類型轉換。
alert( 0 === false ); // false, because the types are different
Comparison with null and undefined
alert( null == undefined ); // true
alert( null === undefined ); // false
alert( null > 0 ); // false ∵ null = 0
alert( null == 0 ); // false ∵ null == undefined
alert( null >= 0 ); // true ∵ null = 0
alert( undefined > 0 ); // false ∵ undefined = NaN
alert( undefined < 0 ); // false ∵ undefined = NaN
alert( undefined == 0 ); // false ∵ null == undefined
不需要記得這麼多,如果值可能出現null
或undefined
,只要使用===
,就可以避免複雜情況發生。
Last updated
Was this helpful?