一、双问号 ??
value1 ?? value2 与 value1 || value2
双问号?? 在 value1 和 value2 之间,只有当 value1 为 null 或者 undefined 时取 value2,否则取 value1;
- 1、在 双问号?? 中,0, false , "" 被认为是有意义的,所以还是取value1;
- 2、在 或 || 中,0, false , "" 和 null,undefined一样都是无意义的,则会取 value2;
双问号 ?? 这个和 或 || 几乎一样,但是它不会屏蔽掉 false和 0,当等于0、false也会返回0、false
const obj = {}
const c_or_d = obj.c ?? 'd'
console.log(c_or_d) // 'd'
console.log(1 || "xx") //1
console.log(0 || "xx") //xx
console.log(null || "xx") //xx
console.log(undefined || "xx") //xx
console.log("" || "xx") //xx
console.log(false"" || "xx") //xx
console.log(1 ?? "xx") //1
console.log(0 ?? "xx") //0
console.log(null ?? "xx") //xx
console.log(undefined ?? "xx") //xx
console.log("" ?? "xx") //""
console.log(false ?? "xx") //false
二、可选链操作符 ?.
定义: 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。
const result = response?.settings?.n ?? 100
如果 response 或者 response.settings 或者 response.settings.n 不存在(值为 null 或者 undefined)时,此时可选链返回undefined,通过??运算符 result 保底值为 100。
常用
通过连接的对象的引用或函数可能是 undefined 或 null 时,可选链操作符提供了一种方法来简化被连接对象的值访问。
const obj = {
info: {
name: 'zhangsan',
age: 20
},
details: {}
}
let someBody = obj.info?.name // zhangsan
let otherInfo = obj.infos?.name // 返回 undefined 而没有报错,保证程序继续执行,而不是中断