js中的空值合并操作符??和可选链操作符?.

空值合并操作符??

  只有当左侧为null和undefined时,才会返回右侧的数

  空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

可选链操作符( ?. )

  可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值

语法:obj?.prop   obj?.[expr]    arr?.[index]    func?.(args)

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

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

 

参考(搬运):https://www.cnblogs.com/zhigu/p/13962661.html

MDN:https://developer.mozilla.org/zh-cn/docs/web/javascript/reference/operators/%E5%8F%AF%E9%80%89%E9%93%BE

posted @ 2021-06-08 10:30  几何柒期  阅读(107)  评论(0编辑  收藏  举报