隐式转换
1.题目:
//1.
console.log(1 + "true");
console.log(1 + true);
console.log(1 + undefined);
console.log(1 + null);
//2.
console.log("2" > 10);
console.log("2" > "10");
// 多个字符从左往右依次比较
console.log("abc" > "b");
console.log("abc" > "aad");
console.log(undefined == undefined);
console.log(undefined == null);
console.log(null == null);
console.log(NaN == NaN);
//3.
console.log([] == 0);
console.log(![] == 0);
console.log(![] == []);
console.log([] == []);
console.log({} == !{});
console.log({} == {});
2.相关知识
-
Number
转换
console.log(Number(null)) //0
console.log(Number("")) //0
console.log(Number(undefined)) //NaN
-
Boolean
转换
let x = 0; //null undefined "" NaN false
console.log(Boolean(x));
//x所取六个值都转换为false
3.解答:
console.log(1 + "true"); //"1true"
console.log(1 + true); // 2
console.log(1 + undefined);
// 1 + Number(undefined) = 1 + NaN = NaN
console.log(1 + null);
// 1 + Number(null) = 1 + 0 = 1
console.log("=============================");
console.log("2" > 10);
// Number("2") = 2 (2 > 10) false
console.log("2" > "10"); //两个字符串比较 Unicode编码,true
// 多个字符从左往右依次比较
console.log("abc" > "b");
// false
console.log("abc" > "aad");
// true
console.log(undefined == undefined); //true
console.log(undefined == null); //true
console.log(null == null); //true
console.log(NaN == NaN); //false
console.log("=============================");
console.log([] == 0); // true
// [].valueOf().toString() = ""
// Number([].valueOf().toString()) = 0
console.log(![] == 0); // true
// ![] 先逻辑Boolean转换,再转换Number
// Boolean([].valueOf().toString()) = false
// Number(false) = 0
console.log(![] == []); // true
// 结合上面两题,Number(false) == Number("")
console.log([] == []); //false 地址不同
console.log({} == !{}); // false
// {}.valueOf().toString() = [object Object]
// Number({}.valueOf().toString()) = NaN
// !{} ---> Boolean({}.valueOf().toString()) = true
// Number(true) = 1
console.log({} == {}); //false