Type (x) |
Type (y) |
Result |
Type (x) ==type (y) |
X===y |
otherwise ... |
False |
Null |
Undefined |
True |
Undefined |
Null |
True |
Number |
String |
X==tonumber (y) |
String |
Number |
Tonumber (x) ==y |
Boolean |
(any) |
Tonumber (x) ==y |
(any) |
Boolean |
X==tonumber (y) |
String or number |
Object |
X==toprimitive (y) |
Object |
String or number |
Toprimitive (x) ==y |
~~~1. Always convert to the same primitive type and make a judgment, 2. Logical values are always converted to numeric types, 3. Numeric types and string type comparisons, always converting strings to numeric values.
Example one:
[0]==ture;
First, the ture will be tonumber, the result is 1, the formula and conversion to [0]==1
Then [0] will be ToString (), the result is "0", the formula is converted to "0" ==1
Then "0" will be Tonumber (), the result is 0, the formula is converted to 0==1
Finally, the formula is converted to 0===1 according to type (x) ==type (y).
So [0]==true will get false
Example two:
"Potato" ==true;
First, True is Tonumber, the result is 1, and the formula translates to "potato" ==1
Then "potato" will be tonumber, the result is Nan, and the formula is converted to Nan==1
According to typeof (X) ==typeof (y), the formula is converted to Nan===1
So the "potato" ==true will get false.
Example three:
Object with GetValue
str = new number (1);
str.tostring = function () {return "2"};
Str==1;
Here typeof str = = "Object", so the STR is toprimitive, this will be valueof to Str is worth 1
So the formula turns into 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 to ToString () to get "2", the formula is "2" ==1
The Tonumber of "2" is 2, and the formula is converted to 2==1.
So obj==1 get False
Example 5:
[]==[]
The left and right are different objects, so false
! []==[]
First of all! []==false, here [] is an object that exists, if it is forced specifically for the bool type, through!! [] get ture, so! []==false, this time the formula for false==[]
Then false is specifically for 0, which is specifically for 0==[]
Then [] specifically for "", the formula is 0== ""
Then "" to 0, the formula for 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