1. 【?】可选链接运算符 – (处理数据未定义、空值的报错)
- 属性中使用:【**?**】
```
this.title = data.children.[0].title
// 1. 若 data 为空,或者 data.children为空 或者data.children[0]为空
console.log(this.title) // 报错
// 解决方案:
if (data && data.length && data.children && data.children.length) {
this.title = data.children[0].title
}
// 使用 可选链接运算符 -- 若其中有空数据的情况,返回undefined(不报错)
this.title = data?.children?.[0]?.title
```
- 在方法中使用:【**?.**】
```
let parent = {
name: "parent",
friends: ["p1", "p2", "p3"],
getName: function() {
console.log(this.name)
}
}
parent.getTitle.() // 报错
parent.getTitle?.() // 不报错,返回 undefined
```
2.【??】 – (为未定义、空值的表达式提供默认值)
// 为空值的情况:
this.title = data?.children?.[0]?.title
// 返回值: undefined
this.title = data?.children?.[0]?.title ?? 'firstName'
// 返回值: firstName
3. 【??=】逻辑空分配
eg: x ??= y ===> x ?? (x = y)
注意: 逻辑空的分配只有在特定条件下才会执行, 即: 只有x值 为 null 或 undefined 时才会执行,否则永不执行。
4.【||=】逻辑或分配
eg:x ||= y ===> x || (x = y)
注意: 逻辑空的分配只有在特定条件下才会执行, 即: 只有x值 为 null / undefined / " " / ' ' / ` ` / 0 / NaN 时才会执行,否则永不执行。
5.【&&=】逻辑与分配
eg: x &&= y ===> x && (x = y)
注意: 逻辑空的分配只有在特定条件下才会执行, 即: 只有x值为true时才会执行,否则永不执行。