大家在笔试前端的时候可能会经常遇见各种 == 相关的比较选择题,个人总结了一下并给予了解释,希望对大家用用处,有错还请指出。
在此之前,大家必须了解一些知识
比较中的转换算法
重点就在于4到9
- Number与String进行比较时,将String转换为Number继续执行比较算法
- 当Object与Number、String进行比较时,将Object转换为String继续执行比较算法
- 当比较中出现Boolean型时,无论对象是啥,将Boolean转化为Number继续执行比较算法
- 数据类型转化为Boolean的规则
- String的 “” 转换为Boolean为false其他都为true
- Number的0和NaN转换为Boolean为false其他都为true
- Object的null转换为Boolean为false其他都为true
- Undefined转换为false 不能转换为true
例:
[] == ![] //true
1.由于!的优先级比较高,先执行![],[]是空数组,数组是对象,由2.3(需要了解的知识文字序号),则[]转换为boolean结果为true,![]结果就为false,表达式变为判断 []==false
2.根据1.3,将false转为Number,结果为0,表达式变为判断 [] == 0
3.根据1.2,将[]变为String,结果为"",表达式变为判断 "" == 0
4.根据1.1,将""变为Number,结果为0,表达式变为判断 0 == 0
返回结果 true
各种例子:
var undefined;
undefined == null; // true
因为变量undefined为定义,typeof undefined == undefined,
undefined与null比较,参见图片第3条,结果true
console.log(1 == true); //文字1.3,Number(true) = 1 -> 1 == 1 true
console.log(2 == true); //文字1.3,Number(true) = 2 -> 2 == 1 false
console.log(0 == false);//文字1.3,Number(false)= 0 -> 0 == 0 true
console.log(NaN == NaN);//图片1.c.i/1.c.ii false
console.log({} == {});//图片1.f {}是对象,比较引用指向的空间,因为是两个不同的空对象,地址也不一样 false
console.log([] == []);//同理
console.log(null == 0);//文字1.2 null是对象,String(null) == "null" -> "null" == 0 ,文字1.1 Number("null") == NaN -> NaN == 0 false
console.log(undefined == 0);//这里将执行String(undefined),之后执行步骤同上
本人新手,说实话写这个查了不少资料,有疑问可以直接回复
注意:图片文档里的8,9的 ToPrimitive(),并非就代表toString(),而代表的是valueOf() 和 toString() 。
顺序:先执行 valueOf(),若得到的值非Number型,再执行toString() ,[] == ![] 这个例子中的3,[]先执行了valueOf(),返回的结果为空引用,则才执行toString返回 “” 。
在JavaScript的==中,总倾向于把双等号两边的值往Number类型转换,而非Boolean类型