# JS 新操作符 —— “?.”、“??”、“??=”
# 1. ?. (可选链式)
说明:
- Optional chaining,可选链式,安全地访问嵌套的对象属性
语法:
obj.prop1?.prop2
obj.prop1?.[expr]
obj.func?.(args)
比较:
// 旧语法
// 如果 && 前一个表达式不是 假值(null、undefined、false、''、0、NaN),则执行后面的表达式
person && person.info && person.info.name
// lodash.get
lodash.get(person, 'info.name');
// 新语法
// 如果 ?. 前一个表达式不是 nullish(null、undefined),则执行后面的表达式
person?.info?.name
示例:
const person = {
// info: {
// name: '张三',
// 2: 'test',
// sayHello(name) {
// console.log('hello', name);
// }
// }
}
console.log( person.info?.name ); // undefined
console.log( person.info?.[1 + 1] ); // undefined
person.info?.sayHello?.('王五'); // undefined
参考:
# 2. ??
说明:
- Nullish coalescing operator
- 逻辑运算符,如果左侧为 nullish(null、undefined)则执行右侧表达式
语法:
leftExpr ?? rightExpr
示例:
false || 'default' // 'default'
false ?? 'default' // false
参考:
# 3. ??=
说明:
- Nullish coalescing assignment
- 赋值操作,如果左侧为 nullish(null、undefined)则将右侧表达式的值赋给左侧
语法:
x ??= y
比较:
// 旧语法
x || x = y
// 新语法
x ??= y
// 新语法等价于
if (x == null) { // <=> (x === null || x === undefined)
x = y;
}
参考:
# 4. babel 配置
说明:
- 可选链操作符是 ES2020 的新特性,如果要在 webpack 5.20 之前的 vue2 项目中使用它,需要对 babel 进行配置
- 如果要编译为 ES5 的语法,也要配置
babel 7.x: ("@babel/core": "^7.12.16"
)
安装
npm i -D @babel/plugin-proposal-optional-chaining ## "@babel/plugin-proposal-optional-chaining": "^7.21.0",
配置 (babel.config.js)
module.exports = { // ... plugins: [ // 放在数组的最后一个位置,在其他插件执行完后再进行代码转换 '@babel/plugin-proposal-optional-chaining', ], };
babel 6.x:
安装
npm i -D @babel/plugin-syntax-optional-chaining
配置 (babel.config.js)
module.exports = { // ... plugins: [ '@babel/plugin-syntax-optional-chaining', ], };
参考:
上一篇: 下一篇:
本章目录