特殊类型比较
不进行类型转化,须要强记;code
null == undefined // true symbol(1) == 1 // false
类型转化( == , > , < , != , >=, <= )对象
boolean, string, number 两两比较会转化为 number进行比较;
Number(boolean) == Number
Number(string) == Numberip
true == 2 // false true == 1 // true true == 0 // false true == '2' // false true == '1' // true true == '0' // false '1' == 2 // false '1' == 1 // true '1' == 0 // false true > 2 // false true > 1 // false true > 0 // true true > '2' // false true > '1' // false true > '0' // true '1' > 2 // false '1' > 1 // false '1' > 0 // true 'null' == 1 // false <=> Number('null') == 1 <=> NaN == 1 'null' == 2 // false 'null' == NaN // false <=> Number('null') == NaN <=> NaN == NaN 'undefined' == 1 // false <=> Number('undefined') == 1 <=> NaN == 1 'undefined' == 2 // false 'undefined' == NaN // false <=> Number('null') == NaN <=> NaN == NaN
若是一个对象与数字或字符串相比较,JavaScript会尝试返回对象的默认值。操做符会尝试经过方法valueOf和toString将对象转换为其原始值(一个字符串或数字类型的值)。若是尝试转换失败,会产生一个运行时错误。字符串
既无自定义valueOf,又无自定义toString,则调用默认toStringget
const a = {name: 'andy'} a == '[object Object]' // true a > '4' // true a > '3' // true a > '2' // true a > 'p' // false <=> a.toString() > 'p' <=> '[object Object]' > 'p' a > 4 // false a > 3 // false a > 2 // false
只存在自定义toString,则调用自定义toStringstring
const a = {name: 'andy'} a.toString = () => 4 a == '[object Object]' // false a == 4 // true a > '4' // false a > '3' // true a > '2' // true
只存在自定义valueOf,则调用自定义valueOfobject
const a = {name: 'andy'} a.valueOf = () => 3 a == '[object Object]' // false a == 3 // true a > '4' // false a > '3' // false a > '2' // true
既存在自定义valueOf,又存在自定义toString方法,则自定义valueOf优先级更高;引用
// 同时存在 valueof 和 toString const a = {name: 'andy'} a.valueOf = () => 3 a.toString = () => 4 a == '[object Object]' // false a == 4 // false a == 3 // true a > '4' // false a > '3' // false a > '2' // true
必须值也相同,才返回true方法
NaN === NaN // false +0 === -0 // true null === null // true undefined === undefined //true
字符串比较基于Unicode 值developer
'5' > '10' // true
对象比较基于引用地址
{} == {} // false new String('foo') == new String('foo') // false new String('foo') == 'foo' // true 隐含了类型转化 <=> new String('foo').valueOf() == 'foo'