这两行代码有何不同,一个抛出错误而另一个不抛出错误?

How are these two lines of code different that one throws an error and the other doesn’t?

console.log("#1", "a12312a".match(/^\d+/)?.[0].length);
console.log("#2", ("a12312a".match(/^\d+/)?.[0]).length);


我在写一些代码时偶然发现了一些我不明白的东西。在 Chrome 89.0.4389.128(官方构建)(64 位)中,上面的代码给出了这个:

#1 undefined
Uncaught TypeError: Cannot read property 'length' of undefined

这两行在我看来是一样的:"a12312a".match(/^\d+/)?.[0] 是一个 undefined,他们正在尝试读取 [=13= 的 属性 length ],它应该抛出一个 TypeError。但是第一行没有,而第二行有。

……为什么?我很困惑。我是否遗漏了一些非常基本的东西?

.match returns null 因为模式不匹配。所以比较在

之间
null?.[0].length

(null?.[0]).length

这应该会使流程更加清晰。对于 .?. 链,当它们从左到右计算时,如果在 任何点 左边的表达式是 nullundefined,链将停在那里并将整个事情评估为 undefined

但是,如果您通过将其中之一括在括号中来打断链条,您只会在括号内得到一个简单的表达式:

(undefined).length

没有可选链的特殊机制。

可选链接仅沿属性 访问和函数调用的连续序列 起作用。中间的任何其他运算符(例如分组括号)都会打断链条。