es6引入Null判断运算符 您所在的位置:网站首页 react判断undefined es6引入Null判断运算符

es6引入Null判断运算符

2023-08-11 06:35| 来源: 网络整理| 查看: 265

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,默认值也会生效。

为了避免这种情况,ES6 引入了一个新的 Null 判断运算符??。

它的行为类似||,但是只有运算符左侧的值为null或undefined时,才会返回右侧的值。

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

Null 判断运算符??有一个运算优先级问题,它与&&和||的优先级孰高孰低。

es6规定:如果多个逻辑运算符一起使用,必须用括号表明优先级,否则会报错。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有