1、==与===的异同
相同点:
1.只要其中一个为NaN一定为false;
2.+0等于-0;
不同点:
===判断机制:
1.数据类型不同一定为false;例:new Boolean(true)===true //false
2.数据相同一定为true;
==判断机制:
1.都为引用类型,指针相同为true;
2.都为原始类型,1、'1'、true 互等,0、' '(/\s+) 、flase互等,null、undefined互等。
3.一方为引用类型,一方为原始类型,将引用类型进行隐式转换(调用toString或者valueOf)再进行比较。
2、对象的隐式转换优先级
原文链接:https://blog.youkuaiyun.com/weixin_42476799/article/details/89330017
Object 默认带有toString
先看看常用的引用类型重写了这两个方法的情况
- Function 重写了 toString()
- Date 重写了 toString() 也重写了 valueOf()
- Array 重写了 toString()
//隐式调用Object.prototype.toString()
//Object
({}).toString() == '[object Object]' //true
//Function
let fn = function () {}
console.log(fn == 'function () {}') //true
let fn = function() {//没有空格
console.log(1)
}
console.log(fn == 'function() {//没有空格\nconsole.log(1)\n}')//true
//Array
var arr = [1,2,3,4,5,2,1,5,2, 1,5]
console.log(arr == '1,2,3,4,5,2,1,5,2,1,5')//true
//Date
let date = new Date('1998-02-23')
console.log(date == 'Mon Feb 23 1998 08:00:00 GMT+0800 (中国标准时间)')//true
console.log(date === 888192000000)//false
console.log(date.valueOf() === 888192000000)//true
所以可以得出结论了,
console.log()直接打印的话中除了object直接打印、date执行两次toString,其余都toString再用valueOf,
alert(),String()中都只使用了toString(),
如果需要进行运算,都是先进行valueOf再toString
总而言之,与数字、运算有关的用valueOf优先,其他都是toString优先
3、 数据的默认Boolean值
3.1new Boolean()与!!的区别
new Boolean(true)为Boolean {true}Boolean对象
!!true为boolean原始值类型
new Boolean(true) === !!true //false
new Boolean(true) == !!true //true
3.2new Boolean(value).valueOf() === !!value
使用!!操作符操作值后的Boolean值
对象:true;
null、undefined、''、+0、-0:false;
'1'、' '(/\s+)、'0':true
比较特殊的转换:
({}) == '[object Object]' //true
!!{} == true //true
' ' == false //true
!!' ' == false //false