1、?. (可选链运算符)
?. 表示:可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每 个引用是否有效。操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值
判断对象的某个属性是否存在,如果存在那么就返回整个属性的值,否则返回undefined
在javascript中如果一个值为null、undefined,直接访问下面的属性,会报 Uncaught TypeError: Cannot read properties of undefined 异常错误。
2、??(空值合并运算符)
?? 表示:只有左侧的值为 null 或 undefined 的时候才返回右侧的值
?? 双问号后面是默认值(可常量、可变量)。
在 ?? 前面没有值的时候会默认 ?? 后边的值(类似于三目运算符中的:后面赋值)
3、??=(空值赋值运算符)
意思是只有当??=左侧的值为undefined、null时,才会把右侧的值赋给左侧,否则左侧不会被赋值
let a;
let b = '123';
let c = 'qwer'
a ??= b;// '123'
b ??= c;// '123'
举个🌰:
(1)这个时候存在detail然后去detail下查找cat属性,因为obj定义了cat所以返回huahua
const obj = {
name: 'ceshi',
detail: {}
}
const name = obj.dog ?. name;
console.log(name) // undefined
const cat = obj.detail ?. cat ?? 'default name'
console.log(cat) // default name
(2)查找obj中detail属性下面name属性,但是对象中没有定义所以值是undefined,这个时候??左侧是undefied那么久使用右侧的数据所以最终返回default name
const obj = {
name: 'ceshi',
detail: {
cat: 'huahua'
}
}
const name = obj.dog ?. name;
console.log(name) // undefined
const cat = obj.detail ?. cat ?? 'default name'
console.log(cat) // huahua