我不确定我是否了解可选链的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条可选的链接之后访问不存在的嵌套属性的任意数量不会再引发错误。
答案 0 :(得分:0)
关于问题的评论可以正确回答。这是一个澄清:
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)。