?? (空值合并运算符) 和 || (逻辑或运算符) 的区别:
?? (空值合并运算符)
-
只检测
null和undefined -
对于
0、false、''、NaN等 假值 ,会正常返回
javascript
let a = null;
let b = undefined;
let c = 0;
let d = false;
let e = '';
console.log(a ?? '默认值'); // '默认值'(null)
console.log(b ?? '默认值'); // '默认值'(undefined)
console.log(c ?? '默认值'); // 0(不是null/undefined)
console.log(d ?? '默认值'); // false(不是null/undefined)
console.log(e ?? '默认值'); // ''(不是null/undefined)
|| (逻辑或运算符)
-
检测所有"假值" (falsy values)
-
假值包括:
false、0、''、null、undefined、NaN
javascript
let a = null;
let b = undefined;
let c = 0;
let d = false;
let e = '';
console.log(a || '默认值'); // '默认值'
console.log(b || '默认值'); // '默认值'
console.log(c || '默认值'); // '默认值'(0是假值)
console.log(d || '默认值'); // '默认值'(false是假值)
console.log(e || '默认值'); // '默认值'(''是假值)