【问题标题】:Optional chaining logic可选的链接逻辑
【发布时间】:2020-07-19 19:35:41
【问题描述】:

我不确定我是否理解了可选链的 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 个可选链接之后访问任意数量的不存在的嵌套属性不会再引发错误。

【问题讨论】:

  • 这就是整个想法。如果您在最后一个缺失的属性之后有一个?,则表达式的其余部分会起作用,因为它会短路。
  • @Pointy 那么为什么示例 #3 会抛出错误?
  • 你用可选的链接标记你不确定的地方,属性访问是否有效。以您确定的情况为例,对象是:a = { b: { c: { d: "value" }}}a = {}。你说a?.b.c.d。如果是第一种情况,它会转到“值”,如果是第二种情况,它会简单地注意到.b的属性访问不存在(undefined),因此它忽略之后的所有内容,并返回@ 987654330@。但是,如果您有 a = { b: {}},则 b 的属性访问权限不是未定义的,它将评估其余部分,然后抛出。
  • @ASDFGerte 换句话说,a?.b 在“旧语法”中是 a || a.b,所以 a?.b.ca || a.b.c - 如果 a.bundefined 则没有什么可以阻止链接。而a?.b?.c 将是a || a.b || a.b.c,因此您可以安全地尝试从undefined 获取.c
  • @alfredopacino 可以看看提案中定义的短路部分:github.com/tc39/proposal-optional-chaining/#short-circuiting

标签: javascript ecmascript-2020


【解决方案1】:

问题上的cmets回答正确。澄清一下:

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 中,截至 2020 年 10 月 27 日,该版本已准备好生产 (LTS)。

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多