直观看懂 ?? || 的区别
2021年2月 · 预计阅读时间: 1 分钟
日常开发中,?? 和 || 的使用,必不可少,那么我们知道何时用 ?? 何时用 || ?。
直观看懂 ?? || 的区别
写在前面#
下面会通过当值为 undefined、null、“”、false、0 来测试使用 ?? || 运算符的结果。
(1)当值为undefined 时:#
const a = undefined;console.log(`a || 'value' --->${a || "value"}`); // 输出 valueconsole.log(`a ?? 'value' --->${a ?? "value"}`); // 输出 value(2)当值为null时:#
const a = null;console.log(`a || 'value' --->${a || "value"}`); // 输出 valueconsole.log(`a ?? 'value' --->${a ?? "value"}`); // 输出 value(3)当值为”” 时:#
const a = "";console.log(`a || 'value' --->${a || "value"}`); // 输出 "value"console.log(`a ?? 'value' --->${a ?? "value"}`); // 输出 ""(4)当值为布尔值false 时:#
const a = false;console.log(`a || 'value' --->${a || "value"}`); // 输出 valueconsole.log(`a ?? 'value' --->${a ?? "value"}`); // 输出 false(5)当值为0 时:#
const a = 0;console.log(`a || 'value' --->${a || "value"}`); // 输出 "value"console.log(`a ?? 66 --->${a ?? "value"}`); // 输出 0总结#
使用 ?? 符号时只有当使用左侧值为 undefined、null 时才会取右右侧的值,而 || 当上面的几种情况都存在时都会取右侧设定的默认值。
我相信大家也会有这样的疑问 ❓,使用 || 时,当左侧的值为 false 的时候都能取到默认值,为什么还要有??这个符号呢,其实这个运算符的一个目的,就是跟链判断运算符?.配合使用,为null或undefined的值设置默认值。