ES6中Null判断运算符(??)正确打开方式-

读取对象属性的时候,如果某个属性的值是null或者undefined,有时候需要为它们指定默认值。常见的作法是通过||运算符指定默认值。

const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;

上面的三行代码都是通过||运算符指定默认值,但是这样写是错的。我们这样写的意愿一般是,只要属性的值为null或者undefined,默认值就会生效。但是属性的值如果是空字符串或者false或者0,默认值也会生效

为了避免这种情况,ES2020引入了一个新的Null判断运算符??。它的行为类似于||,但是只有运算符左侧的值为null或者undefined时,才会返回右侧的值。

const headerText = response.settings.headerText ?? 'Hello, world!';
const animationDuration = response.settings.animationDuration ?? 300;
const showSplashScreen = response.settings.showSplashScreen ?? true;

上面代码中,默认值只有左侧属性值为null或者undefined时,才会生效

这个运算符的一个目的,就是跟链判断符?.配合使用,为null或者undefined的值设置默认值

const value = respons.setting?.value ?? 300

上面的代码中,如果response.setting时null或者undefined,或者response.setting.value是null或者undefined,就会返回默认值300。也就是说,这一行代码包括了两级属性的判断

这个运算符很适合判断函数参数使得否赋值

function Component(props){
    const enabled = props.enabled ?? true
    // ...
}

上面的代码判断props参数enabled属性是否赋值,基本等同于下面的写法

function Component(props){
    const { enabled:enable=true} = props
    // ....
}

?? 本质上是逻辑运算,它与其他两个逻辑运算符&&和||有一个优先级问题,它们之间的优先级到底谁高谁低。优先级的不同,往往会导致逻辑运算结果不同。

现在的规则是,如果多个运算符一起使用,必须用括号表明优先级,否则会报错

// 报错
lhs && middle ?? rhs
lhs ?? middle && rhs
lhs || middle ?? rhs
lhs ?? middle || rhs

上面四个表达式都会报错,必须加入标明优先级的括号

(lhs && middle) ?? rhs;
lhs && (middle ?? rhs);

(lhs ?? middle) && rhs;
lhs ?? (middle && rhs);

(lhs || middle) ?? rhs;
lhs || (middle ?? rhs);

(lhs ?? middle) || rhs;
lhs ?? (middle || rhs);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值