JavaScript值的比较小记

202 阅读1分钟

字符串比较

比较字符串的大小时,JavaScript 会使用“字典(dictionary)”或“词典(lexicographical)”顺序进行判定。 也就是说字符串比较是按字符(母)逐个进行的

栗子:

console.log( "abcd" < "aeg" );  // true 
先比较a然后比较b和e 由于e>b 后续cd就不会往下比较

奇怪的结果:null vs 0

console.log( null > 0 );  // (1) false
console.log( null == 0 ); // (2) false
console.log( null >= 0 ); // (3) true

特立独行的 undefined

console.log( undefined > 0 ); // false (1)
console.log( undefined < 0 ); // false (2)
console.log( undefined == 0 ); // false (3)

与运算 && 在或运算符 || 之前执行

与运算 && 的优先级比或运算 || 要高。 下面两个代码是一样的:

a && b || c && d 

(a && b) || (c && d)

a && b 表达式与加了括号的 (a && b)是一样