[英]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 (Official Build) (64-bit) 中,上面的代码给出了这个:
#1 undefined
Uncaught TypeError: Cannot read property 'length' of undefined
这两行在我看来都一样: "a12312a".match(/^\d+/)?.[0]
是undefined
,他们正在尝试读取undefined
的属性length
,这应该会抛出TypeError
。 但是第一行没有,而第二行没有。
…为什么? 我很困惑。 我错过了一些非常基本的东西吗?
.match
返回 null 因为模式不匹配。 所以比较是在
null?.[0].length
和
(null?.[0]).length
这应该使过程更清晰。 与.
和?.
链,当它们从左到右评估时,如果在任何时候左边的表达式是null
或undefined
,链将停在那里并将整个事情评估为undefined
。
但是,如果您通过将其中一个括在括号中来打破链,您只会在括号内得到一个简单的表达式:
(undefined).length
没有可选链的特殊机制。
可选链接仅在属性访问和 function 调用的连续序列中起作用。 介于两者之间的任何其他运算符(例如分组括号)都会破坏链。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.