三元运算符?:也常用于判断对象是否存在。
eg:
```javascript
const fooValue = fooInput ? fooInput.value : undefined
上面例子中,必须先判断fooInput是否存在,才能读取fooInput.value。
这样的层层判断非常麻烦,因此 ES2020 引入了“链判断运算符”(optional chaining operator)?.,简化上面的写法。
const fooValue = fooInput ?. fooInput.value : undefined
链判断运算符?.有三种写法。
obj?.prop //变量
obj?.[expr] //对象
arr?.[index] //数组
func?.[argu] //函数
如果在你不确定某个值是否为undefined或null时,可以使用?.可选链
eg:
let obj={a:1,b:2}
console.log(obj.c.d, 'ccc');//报错( Cannot read properties of undefined (reading 'd'))
如果把.关键词换成?.关键词:
console.log(obj.c?.d, 'ccc'); //undefined 'ccc'
下面是?.运算符常见形式,以及不使用该运算符时的等价形式。
a?.b
// 等同于
a == null ? undefined : a.b
a?.[x]
// 等同于
a == null ? undefined : a[x]
a?.b()
// 等同于
a == null ? undefined : a.b()
a?.()
// 等同于
a == null ? undefined : a()
可选链嵌套使用:
??的作用
当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”
## 空值合并操作符(??)
**只有当左侧为null和undefined时,才会返回右侧的数
空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。**
应用:
一般调接口取数据时判断后端返回null数据时可用,
时间返回null或undefined时可展示--
res.data.time?? '--'