Js中? ?和? .

Js中??和?.和 ||

空值合并操作符 ??

只有当左侧为null或者undefined的时候才输出右侧的值

逻辑或操作符 ||

左侧的值为假值的时候就输出右侧的数

假值:
null undefined '' 0
例子:
console.log(null ?? 'ss')   // 输出ss
console.log(undefined ?? 'ss')   // 输出ss
console.log(0 ?? 'ss')   // 输出0
console.log(0 || 'ss')   // 输出ss

可选链操作符 ?.

允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName); // undefined
console.log(adventurer.someNonExistentMethod?.()); //undefined
空值合并操作符可以在使用可选链时设置一个默认值:

let a = {
  name: "Carl",
  details: { age: 82 }
};

let aCity = a?.city ?? "城市";
console.log(aCity);  // “城市”
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值