ES6新增


作用:判断某个属性是否存在

1.常规

  1. // 错误的写法
  2. const firstName = message.body.user.firstName || 'default';
  3. // 正确的写法
  4. const firstName = message?.body?.user?.firstName || 'default';
  5. //下面是判断对象方法是否存在,如果存在就立即执行的例子。
  6. iterator.return?.()

2. ?. 判断某个变量或方法是都定义

  1. //之前
  2. let a=mes.name?mes.name:"哇哈" //同上
  3. //现在
  4. const firstName = message?.body?.user?.firstName || '哇哈';

3. ?? Null判断运算符

  1. //之前
  2. let a=mes.name||"哇哈" //当mes.name 为null或undefiend执行默认操作,但如果mes.name=0或false也会运行
  3. //现在
  4. let a=mes.name??"娃哈"//只有mes.name为null或undefiend执行默认操作
  5. //主要是配合?.使用
  6. let a=mes?.name??"娃哈"//只有mes.name为null或undefiend执行默认操作

?? || && 优先级

  1. //报错
  2. a&&b??res //a和b为null或者undifined 值为res
  3. //正确写法
  4. (a&&b)??res

4.其他运算符

??= ||= &&=

  1. // 或赋值运算符
  2. x ||= y
  3. // 等同于
  4. x || (x = y)
  5. // 与赋值运算符
  6. x &&= y
  7. // 等同于
  8. x && (x = y)
  9. // Null 赋值运算符
  10. x ??= y
  11. // 等同于
  12. x ?? (x = y)
  13. //用法
  14. // 老的写法
  15. user.id = user.id || 1;
  16. // 新的写法
  17. user.id ||= 1;