欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

ES6 链式判断运算符 (?...) 和 Null 判断运算符 (???)

最编程 2024-05-03 20:28:29
...

一、语法介绍

obj?.prop:判断 obj.prop属性是否存在,没有就返回undefined

obj?.[expr]:判断obj[expr]属性是否存在,没有就返回undefined

arr?.[index]:判断 obj[index]属性是否存在,没有就返回undefined

func?.(args):如果存在 func()就执行,没有就返回undefined

# 链判断运算符(?.)

// 错误的写法
const  firstName = message.body.user.firstName;

// 正确的写法
const firstName = (message
  && message.body
  && message.body.user
  && message.body.user.firstName) || 'default';

解决方法

const firstName = message?.body?.user?.firstName || 'default';

短路机制

?.运算符相当于一种短路机制,只要不满足条件,就不再往下执行。
a?.[++x]
// 等同于
a == null ? undefined : a[++x]

二、Null 判断运算符(??)

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

  1. || 属性的值为null、undefined、为空字符串、false、0,默认值就会是 || 右边的值
  2. ?? 只有运算符左侧的值为null或undefined时,才会返回右侧的值

优先级

??有一个运算优先级问题,它与&&和||的优先级孰高孰低。现在的规则是,如果多个逻辑运算符一起使用,必须用括号表明优先级,否则会报错

// 报错
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);