optional chaining (?.
)
?.
运算符用于访问对象属性和调用函数,如果访问的对象或者调用的函数是 undefined
或者 null
,则表达式会直接返回 undefined
而不会报错。
const nestedProp = obj.first?.second;
// 等价于
const temp = obj.first;
const nestedProp =
temp === null || temp === undefined
? undefined
: temp.second;
基本使用场景
- 作用于对象属性访问:
obj.first?.second?.thrid
- 作用于函数调用:
someInterface.customMethod?.()
在函数调用场景下
- 作用于表达式:
obj?.["prop" + "Name"]
// 在数组场景同样适用,因为数组也是使用方括号访问
arr?.[42]
在作用于表达式的场景,如果左操作数是 null
或 undefined
,则表达式将不会被执行:
const potentiallyNullObj = null;
let x = 0;
const prop = potentiallyNullObj?.[x++];
console.log(x); // 0 as x was not incremented
Map
场景:
const myMap = new Map();
myMap.set("JS", { name: "Josh", desc: "I maintain things" });
const nameBar = myMap.get("CSS")?.name;
- 与空值合并运算符结合使用:
customer?.city ?? "Unknown city"
错误使用场景
- 尝试对
?.
的结果进行赋值:
object?.property = 1; // 语法错误
- 尝试与标签模板搭配使用
String.raw?.`Hello, world!`; // 语法错误
- 尝试与
new
表达式搭配使用:
new Map?.(); // 语法错误