持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情
上一篇文章说到了其他类型与布尔值的比较,这篇文章我们继续~
例子:null与undefined
null与undefined进行宽松相等(==)比较时,它们是相等的,它们与自身也相等,它两在宽松相等中是一回事,可以相互进行隐式强制类型转换。
const a = null;
const b;
a == b; // true --> null == undefined
a == null; // true --> null == null
b == null; // true --> undefined == null
b == undefined; // true --> undefined == undefined
a == false; // false --> null == false
b == false; // false --> undefined == false
a == ""; // false --> null == ""
b == ""; // false --> undefined == ""
a == 0; // false --> null == 0
b == 0; // false --> undefined == 0
在ECMAScript中null与undefined的宽松相等有以下规则:
- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
也就是:
- 如果 x 为 null,y 为 undefined,则结果为 true。
- 如果 x 为undefined,y 为 null,则结果为 true。
那么知道这个有什么用呢?
举个例子,我们都知道,如果一个函数没有指定返回值,那么该函数执行完毕将默认返回undefined,在我们需要判断某个函数的返回值的时候,就可以利用null和undefined宽松相等。
const test = (arg1) => {
if(arg1===1) return true
}
const a1 = test(1) // true
const a2 = test(2) // undefined
if(a1 == null){ // false
// ...
}
if(a2 == null){ // true
// ...
}
这个例子就简单的用到了nul和undefined,它们之间的强制类型转换是安全可靠的。
下面是显示的做法,感觉会更繁琐一些:
if(a1 === undefined || a === null ){
// ...
}
例子:对象与非对象
对于对象类型(对象/函数/数组)和标量基本类型(字符串/数字/布尔值)之间的相等比较:
const a = 66
const b = [66]
a == b // true
[66]首先通过ToPrimitive进行抽象操作,得到原始值"66",变成进行66 == "66"的比较,然后隐式转换成 66 == 66,隐式转换上一章提到过,所以结果就是true。
在ECMAScript中null与undefined的宽松相等有以下规则:
- If Type(x) is either String or Number and Type(y) is Object,
return the result of the comparison x == ToPrimitive(y). - If Type(x) is Object and Type(y) is either String or Number,
return the result of the comparison ToPrimitive(x) == y.
- 如果 x 为 String或者Number,y 为 Object,则返回x == ToPrimitive(y)的结果。
- 如果 x 为 Object,y 为 String或者Number,则返回ToPrimitive(x) == y的结果。