可选链操作符( ?. )
描述
可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效
?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值
举例
const adventurer = {<br> name: 'Alice',<br> cat: {<br> name: 'Dinah'<br> }<br>};<br><br>const dogName = adventurer.dog?.name;<br>console.log(dogName);<br>// expected output: undefined<br><br>console.log(adventurer.someNonExistentMethod?.());<br>// expected output: undefined
语法
obj?.prop
let myMap = new Map();<br> myMap.set("foo", {name: "baz", desc: "inga"});<br><br> let nameBar = myMap.get("bar")?.name;
obj?.[expr]
可选链与表达式:
let nestedProp = obj?.['prop' + 'Name'];
arr?.[index]
可选链访问数组:
let arrayItem = arr?.[42];
func?.(args)
函数调用
let result = someInterface.customMethod?.();<br>如果希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写 someInterface?.customMethod?.()
短路计算
let potentiallyNullObj = null;<br>let x = 0;<br>let prop = potentiallyNullObj?.[x++];<br><br>console.log(x); // x 将不会被递增,依旧输出 0<br><br>当在表达式中使用可选链时,如果左操作数是 null 或 undefined,表达式将不会被计算
连用可选链操作
let customer = {<br> name: "Carl",<br> details: {<br> age: 82,<br> location: "Paradise Falls" // details 的 address 属性未有定义<br> }<br>};<br>let customerCity = customer.details?.address?.city;<br><br>// … 可选链也可以和函数调用一起使用<br>let duration = vacations.trip?.getTime?.();
空值合并操作符可以在使用可选链时设置一个默认值:
let customer = {<br> name: "Carl",<br> details: { age: 82 }<br>};<br><br>let customerCity = customer?.city ?? "暗之城";<br>console.log(customerCity); // “暗之城”