JavaScript different types of object comparison rules
Example one:
[0]==true;
First Tonumber True, the result is 1, the formula is converted to [0]==1
then [0] will be ToString (), the result is "0", the expression translates to "0" ==1
then "0" will be Tonumber (), the result is 0, The formula is converted to 0==1 is finally converted to 0===1 So [0]==true will get false
example two:
"potato" = = True
first true will be tonumber, the result is 1, the formula translates to "potato" ==1
then "potato" will be tonumber, resulting in Nan, Nan==1
based on typeof (X) ==typeof ( Y), convert to Nan===1
so "potato" ==true get false
example three:
object with Getvalue
str = new number (1),
str.tostring = function () {return "2"};
str==1;
here typeof str = = "Object", so toprimitive str, this will be valueof for STR is worth 1 Span style= "COLOR: #3f3f3f" >
so the equation translates to 1==1
so str==1 get True
example four:
object with Tostring
var obj = {
toString: function () {return ' 2 '}
};
obj==1
here typeof obj = = "Object ", toprimitive to obj, first valueof get object, continue ToString () to get" 2 ", the formula is" 2 "==1
For "2" Tonumber get 2, the formula to 2==1
so obj==1 get false
example 5:
[]==[]
is a different object around, so False
! []==[]
first! []==false, here [] is an object that exists, if it is forced specifically for the bool type, through!! [] get ture, so! []==false, this is specifically for false==[]
and then false for 0, which is specifically for 0==[]
and then [] specifically for "", The 0== ""
then "" to 0, The 0==0
so![] ==[] Get true
Example 6:
! {}=={}
First of all! {} is designed to be false, and rules and 5 are converted to false=={}
False for 0, the formula is converted to 0=={}
Toprimitive for {} gets "[Object Object]", which is specifically 0== "[Object Object]"
Tonumber for "[Object Object]" gets NaN, which is specifically for 0==nan
So! {}=={} Get false
transferred from:http://www.cnblogs.com/simayixin/archive/2011/03/21/1990831.html
JavaScript different types of object comparison rules