javascript关于"=="的隐式转换规则(干货)

String VS Number

string将会转化成number去作比较

"42" == 42 // true 42 == 42

Anything VS Boolean

boolean值将首先转化成number类型, 0或者1. 然后再进行比较

"42" == true // false "42" == 1 ---> 42 == 1

null VS undefined

null == undefined // true 设定这样, 记住就行. 除了这一对外, 其他的值和他们比都返回false

Object VS non-Object

如果object/function/array与一个基本类型的数据作对比(string or number), 首先将对象转换成基本类型数据.

ToPrimitive转换函数,会调用valueOf()如果有必要, 还会调用toString()

来看一些例子

[] == ![]; // true [] == false --> [] == 0 --> "" == 0 --> 0 == 0
2 == [2]; // true  2 == "2" --> 2 == 2
"" == [null]; // true  "" == ""  (ps: String([null]) === "";  String(null) === "null")
"0" == false; // true "0" == 0 --> 0 == 0
false == 0; // true 0 == 0
false == ""; // true 0 == "" --> 0 == 0
false == []; // true 0 == [] --> 0 == "" --> 0 == 0
"" == 0; // true 0 == 0
"" == []; // true "" == ""
0 == []; // true 0 == "" --> 0 == 0

附上一张javascript相等判断表:

javascript关于

(Source: https://github.com/dorey/JavaScript-Equality-Table)

You-Dont-Know-JS/types & grammar

你可能感兴趣的:(javascript,javascript,==,隐式转换,判断)