js中的隐式转换

 1 == true   // true

 2 == true   // fase

 

在使用 == 比较的时候,会进行隐式转换

 In this case 2 is number and true is boolean. The conversion rule is "while comparing a number to boolean, boolean will be converted to number" hence

当拿数字与boolean对比的时候,boolean会被隐式转换为数字

 

NaN = NaN //false     NaN不等于任何值 (除非使用Object.is,NaN等于NaN

[] == false // true

[] == ![] // true

0 == '0' // true     // If Type(x) is Number and Type(y) is String,return the result of the comparison x == ToNumber(y)

0 == []  // true // If Type(x) is either String or Number and Type(y) is Object,return the result of the comparison x == ToPrimitive(y).

[] == '0'  // false   // If Type(x) is Object and Type(y) is either String or Number,return the result of the comparison ToPrimitive(x) == y.

 

 

 

 

 

 

 

更多练习:

 

Boolean([]) //true;
Boolean({}) //true;


[] == ![] //true
// 1. 在比较时 先计算右边,[]是true !true是false, 最终在比较时被转为0
// 2. 比较string、number和引用类型时,会调用引用类型的toString 于是[].valueOf 变成了''
// 3. 判断'' == 0, 所以返回true

{} == !{} // false
// 1. 在比较时 先计算右边,{}是true !true是false,最终最比较时被转为0
// 2. 比较string、number和引用类型时,会调用引用类型的toString 于是{}.toString 变成了'[object Object]'
// 3. 判断'[object Object]' == 0, 所以返回false

 

 

 

1 == true  

2 == true // false

NaN = NaN // false

[] == false  

[] == ![]  

0 == '0'  

0 == []  

[] == '0'   // false

 

 

posted @ 2020-06-10 01:46  hh9515  阅读(152)  评论(0)    收藏  举报