Js中??和?.和 ||
空值合并操作符 ??
只有当左侧为null或者undefined的时候才输出右侧的值
逻辑或操作符 ||
左侧的值为假值的时候就输出右侧的数
假值:
null undefined '' 0
例子:
console.log(null ?? 'ss') // 输出ss
console.log(undefined ?? 'ss') // 输出ss
console.log(0 ?? 'ss') // 输出0
console.log(0 || 'ss') // 输出ss
可选链操作符 ?.
允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
?.
操作符的功能类似于 .
链式操作符,不同之处在于,在引用为空(nullish ) (null
或者 undefined
) 的情况下不会引起错误,该表达式短路返回值
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName); // undefined
console.log(adventurer.someNonExistentMethod?.()); //undefined
空值合并操作符可以在使用可选链时设置一个默认值:
let a = {
name: "Carl",
details: { age: 82 }
};
let aCity = a?.city ?? "城市";
console.log(aCity); // “城市”