JS 中的||、??、?.

@see js中??和?.的意思

逻辑或操作符||

逻辑或操作符||在左侧操作数为假值时返回右侧操作数。也就是说,如果使用||来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。

null || 'default';  // 返回`default`
'' || 'default';    // 返回`default`
'abc' || 'default'; // 返回`abc`

空值合并操作符??

  空值合并操作符??只有当左侧为nullundefined时,才会返回右侧的数.

null ?? 'default';  // 返回`default`
'' ?? 'default';    // 返回``
'abc' ?? 'default'; // 返回`abc`

可选链操作符?.

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

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

console.log(adventurer.dog?.name); // 返回`undefined`
console.log(adventurer.someNonExistentMethod?.()); // 返回`undefined`

// 如果希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写:
someInterface?.customMethod?.()
示例
# 以前一般这样使用:
let nestedProp = obj.first && obj.first.second;

# 或者这样:
let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);

# 现在我们这样使用:
let nestedProp = obj.first?.second; // 访问属性
let result = someInterface.customMethod?.(); // 调用方法
let nestedProp = obj?.['prop' + 'Name']; // 表达式
let arrayItem = arr?.[42]; // 访问数组