Javascript 可选链接逻辑

Javascript 可选链接逻辑,javascript,ecmascript-2020,Javascript,Ecmascript 2020,我不确定我是否了解可选链接的js实现背后的逻辑 const a = {b:1} 1 > console.log(a?.c) => undefined 2 > console.log(a?.c?.d) => undefined 3 > console.log(a?.c.d) => Uncaught TypeError: Cannot read property 'd' of undefined 一切都是有意义的。然后: 4 > conso

我不确定我是否了解可选链接的js实现背后的逻辑

const a = {b:1}

1 > console.log(a?.c)     => undefined
2 > console.log(a?.c?.d)  => undefined
3 > console.log(a?.c.d)   => Uncaught TypeError: Cannot read property 'd' of undefined
一切都是有意义的。然后:

4 > console.log(a?.c?.d.e) => undefined
5 > console.log(a?.c?.d.e.f.g) => undefined

访问未定义的属性会引发错误(#3),但在2个可选链接之后访问任意数量的不存在的嵌套属性不会再引发错误。

关于该问题的注释正确回答了该问题。这里有一个澄清:

console.log(a.c)     // undefined
console.log(a.c.d)   // Uncaught TypeError: Cannot read property 'd' of undefined
console.log(a.c.d.e)   // Uncaught TypeError: Cannot read property 'd' of undefined
console.log(a.c?.d)  // undefined
console.log(a.c?.d.e) // undefined
console.log(a.c?.d.e.f.g) // undefined
您可以看到,求值总是在c处停止,因为没有属性a.c。当求值停止时,如果您使用了可选的链接运算符(?),它将返回未定义,如果没有,它将抛出一个错误


请注意,这是最近的一项功能。对于nodejs来说,它出现在版本14中,从2020年10月27日起,该版本已准备好生产(LTS)。

这就是整个想法。如果在最后一个缺少的属性之后有一个
,则表达式的其余部分会工作,因为它短路。@Pointy那么为什么示例#3会引发错误?您可以使用可选链接标记不确定属性访问是否工作的位置。假设您确信对象是:
a={b:{c:{d:{d:{value}}}
a={}
。你说的是
a?.b.c.d
。如果是第一种情况,它会转到“value”,如果是第二种情况,它只会注意到,
.b
的属性访问不存在(
undefined
),因此它会忽略后面的所有内容,并返回
undefined
。但是,如果您有
a={b:{}
,则
b
的属性访问权限不是未定义的,它将计算其余的,这将抛出。@ASDFGerte换句话说,
a?.b
是“旧语法”中的
a|a.b
,因此
a?.b.c
a | | a.b.c
-如果
a.b
未定义的
,则没有什么可以停止链接。鉴于
a?.b?.c
将是
a | | a.b | | a.b.c
,因此您可以安全地从
未定义的
中获取
.c
。@Alfredpacino或许可以查看提案中定义的短路部分: