可选链运算符(?.)的连续性
可选链运算符(?.)允许读取位于连接对象链深处的属性的值。在引用为空的情况下不会引起错误,该表达式短路返回值是 undefined
。
因为返回值是 undefined
,所以后续的.
对于 undefined
不存在的方法或对象同样需要使用可选链运算符(?.)。
eg:
// 对于对象
shopData: [
{
name: "点菜",
data: {
content: "点菜",
items: [
{
text: "热销套餐",
children: [
xxx
],
},
{
text: "超级折扣",
children: [
xxx
],
},
],
},
},
{
name: "评价",
data: {
content: "评价",
},
},
{
name: "商家",
data: {
content: "商家",
},
},
],
要遍历两个children
下的内容,需要
shopData.forEach((item) => {
item.data?.items?.forEach((item) => {
item.children.forEach((item) => {
xxx
});
});
});
item.data?.items
表面看,已经选到(或者确定)了 点菜
下的 items
,该 items
是个数组,接着调用确定的数组的.forEach
方法为什么还要加.?
呢?
因为此时的data
结构:
(property) data: {
content: string;
items: {
text: string;
children: {
xxx
}[];
}[];
} | {
content: string;
items?: unknown;
}
可以看到后面两个不存在items
的data
并不是说消失了,仍然被遍历且有一个类型为unknown
的items
。
如果此时直接.forEach
,会报Property 'forEach' does not exist on type 'unknown'.
,因为显然unknown
上不存在forEach
.
个人理解浅显,如有错误还请指教。