【发布时间】:2021-07-16 09:21:03
【问题描述】:
console.log("#1", "a12312a".match(/^\d+/)?.[0].length);
console.log("#2", ("a12312a".match(/^\d+/)?.[0]).length);
我正在编写一些代码,偶然发现了一些我不理解的东西。在 Chrome 89.0.4389.128 (Official Build) (64-bit) 中,上面的代码给出了这个:
#1 undefined
Uncaught TypeError: Cannot read property 'length' of undefined
这两行在我看来是一样的:"a12312a".match(/^\d+/)?.[0] 是一个undefined,他们正在尝试读取undefined 的属性length,它应该抛出一个TypeError。但是第一行没有,而第二行有。
……为什么?我糊涂了。我错过了一些非常基本的东西吗?
【问题讨论】:
标签: javascript optional-chaining