quiz:
// 1st step
false == '0'
// 2nd step
Number(false) == '0' -> 0 == '0'
// 3rd step
0 == '0' -> 0 == Number('0')
// 4th step
0 == 0 -> 0 === 0 -> true
solution:
there is a hierarchy for type coercion in JavaScript. The coercion process follows a set of rules:
- If either operand is a
null
orundefined
, they are considered equal (unless strict equality is being used with the "===" operator).
先檢查是否null或undefined - If either operand is a boolean, the boolean is converted to a number (false becomes 0, true becomes 1) before comparison.
布林值轉數字 - If one operand is a string and the other is a number, the string is converted to a number before comparison.
字串和數字比的話,字串轉數字 - If one operand is an object and the other is a primitive value, the object is converted to its primitive value before comparison. This can be done using the
valueOf()
ortoString()
methods of the object. - If the operands are both strings, they are compared as strings.
後兩個比較深,先跳過
沒有留言:
張貼留言