可选链逻辑

4

我不确定 JavaScript 可选链实现背后的逻辑。

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),但是在两个可选链之后访问任意数量的不存在的嵌套属性不再抛出错误。


1
这就是整个想法。如果在最后一个缺失的属性后面加上 ?,那么表达式的其余部分就会正常工作,因为它会短路。 - Pointy
@Pointy那为什么例子#3会抛出错误? - alfredopacino
2
你可以使用可选链来标记你不确定属性访问是否有效的位置。假设你确定对象只可能是这两种情况之一:a = { b: { c: { d: "value" }}}a = {}。你可以写成 a?.b.c.d。如果是第一种情况,它会返回"value";如果是第二种情况,它会发现.b属性不存在(undefined),所以忽略后面的内容并返回undefined。但是,如果你有a = { b: {}},那么对b属性的访问不是undefined,它将计算剩下的内容,这会导致错误。 - ASDFGerte
1
换句话说,a?.b 在“旧语法”中等同于 a || a.b,因此 a?.b.c 等同于 a || a.b.c - 如果 a.bundefined,那么就没有阻止链接的东西。而 a?.b?.c 将是 a || a.b || a.b.c,因此您可以安全地避免从 undefined 中获取 .c - VLAZ
2
@alfredopacino 或许可以看一下提案中定义的短路部分:https://github.com/tc39/proposal-optional-chaining/#short-circuiting - Nick Parsons
显示剩余2条评论
1个回答

0
问题的评论已经正确回答了。这里是一个澄清:
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。当它停止时,如果您使用了可选链接运算符(?.),它将返回 undefined,否则会抛出错误。

请注意,这是一个最近的功能。对于 nodejs,它出现在版本14中,该版本已经准备好用于生产(LTS),截至2020/10/27。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接