我们在网上查找一些解决方法时,会看到很多这样的代码。
//类型1
let result = date[day] ?? 'default';
//类型2
let num = obj.data?.nums?.first;
?? 其实就是空值合并操作
当左侧值为null 或 undefined 时,返回 ?? 符号右边的值
'hello world' ?? 'hi'
// 'hello world'
'' ?? 'hi'
// ''
false ?? 'hi'
// false
null ?? 'hi'
// 'hi'
undefined ?? 'hi'
// 'hi'
? 可选链操作符
允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
let network = {
chain: 1,
name: 'ethereum'
}
let res = network?.name
// 返回 ethereum
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // details 的 address 属性未有定义
}
};
// 由于 details 中 address 属性未有定义, 因此返回 undefined
let customerCity = customer.details?.address?.city;
//会报错,不能读取到city属性 Uncaught TypeError: Cannot read properties of undefined (reading 'city')
let customerCity = customer.details.address.city;