ES6——可选链(链判断运算符 )and 空值合并操作符(??)



三元运算符?:也常用于判断对象是否存在。
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?? '--'


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值