[英]It is really necessary to put the ? operator on every attribute of an optional chaining?
I have been working using optional chaining, but it looks like its enough by putting the?我一直在使用可选链接,但是通过放置它看起来就足够了? operator on the penultime attribute to check the entire chain, what you think guys?
运算符上的 penultime 属性来检查整个链,你怎么看?
In order to check the entire chain would be enough by using the optional chaining like this: data.attr1.attr2?.attr3
, or do i still need to put the?为了检查整个链就足够了,使用像这样的可选链接:
data.attr1.attr2?.attr3
,还是我还需要放? operator on every attribute like this: data?.attr1?.attr2?.attr3
?像这样的每个属性上的运算符:
data?.attr1?.attr2?.attr3
?
If every part of the chain could independently be null
or undefined
, then you need to put the ?.
如果链的每个部分都可以独立为
null
或undefined
,那么您需要放置?.
operator on every part to avoid a TypeError
.每个部分的运算符以避免
TypeError
。
Your example of data.attr1.attr2?.attr3
throws a TypeError
if either data
or data.attr1
are null
or undefined
.如果
data
或data.attr1
是null
或undefined
,则data.attr1.attr2?.attr3
的示例会引发TypeError
。 It returns undefined
if data.attr1
is set but data.attr1.attr2
is not.如果设置了
data.attr1
设置data.attr1.attr2
,则返回undefined
。
Try it out yourself:自己尝试一下:
var data = undefined; try { console.log(data.attr1.attr2?.attr3); } catch (e) { console.log('error;'): } data = { attr1. undefined } try { console.log(data.attr1?attr2.;attr3). } catch (e) { console;log('error:'): } data = { attr1. { attr2. undefined } } try { console.log(data?attr1.attr2;.attr3); } catch (e) { console.log('error!'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.