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

Кон*_*Ван 5 javascript optional-chaining

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


我在写一些代码时偶然发现了一些我不明白的东西。在 Chrome 89.0.4389.128 (Official Build) (64-bit) 中,上面的代码给出了这个:

#1 undefined
Uncaught TypeError: Cannot read property 'length' of undefined
Run Code Online (Sandbox Code Playgroud)

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

…为什么?我糊涂了。我错过了一些非常基本的东西吗?

Cer*_*nce 6

.match由于模式不匹配,因此返回 null。所以比较是

null?.[0].length
Run Code Online (Sandbox Code Playgroud)

(null?.[0]).length
Run Code Online (Sandbox Code Playgroud)

这应该使过程更加清晰。使用.?.链,当它们从左到右求值时,如果左边的表达式在任何时候nullundefined,则链将停在那里并将整个事物求值为undefined

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

(undefined).length
Run Code Online (Sandbox Code Playgroud)

没有可选链的特殊机制。

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