?. ?? 是 JavaScript 中的两个新操作符,分别是可选链操作符(optional chaining operator)和空值合并操作符(nullish coalescing operator)。

?. 操作符

?. 可选链操作符用于访问可能为空或未定义的属性或方法,它允许我们安全地访问嵌套对象的属性,如果中间的属性为空或未定义,则不会抛出错误,而是返回 undefined。例如:

const obj = {
  foo: {
    bar: 123
  }
};
// 普通访问属性的方式
const x = obj.foo.bar; // x = 123
// 使用可选链操作符
const y = obj?.foo?.bar; // y = 123
// 如果对象未定义,则返回 undefined
const z = undefined?.foo?.bar; // z = undefined

?? 操作符

?? 空值合并操作符用于检查一个变量是否为 null 或 undefined,如果是,则返回一个默认值,否则返回该变量的值。与传统的逻辑运算符 || 不同,?? 只会在左侧的值为 null 或 undefined 时返回右侧的默认值,对于其他假值(如空字符串、0、false 等)并不会返回默认值,而是会返回它本身。例如:

const x = undefined ?? 'default'; // x = 'default'
const y = null ?? 'default'; // y = 'default'
const z = 'value' ?? 'default'; // z = 'value'

需要注意的是,?? 操作符需要在 ES11 及以上的版本才能使用。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。