gpt4 book ai didi

typescript : question mark on array

转载 作者:行者123 更新时间:2023-12-03 19:16:14 27 4
gpt4 key购买 nike

这是我的代码的骨架:

var myArray: (Array<any> | null);
if (cnd) {
myArray = [];
myArray?.push(elt); // Question 1
myArray[0].key = value; //Question 2
} else {
myArray = null;
}

问题1:为什么需要 ?? myArray 已分配给一个空数组。

问题 2:避免错误的语法是什么:对象可能为空。

谢谢你的回答。

最佳答案

对于问题1,你可以引用这个link

对于问题 2,在访问您的对象之前,只需像这样对 null 执行检查

if (obj !== null) {
obj.doSomeThing();
}

或者,如果您的对象可以是 nullundefined ,则只需如下所示。 nullundefined 是所谓的假值,所以当它们在 bool 上下文中使用时,它们会被自动强制转换为 false
if (obj) {
obj.doSomeThing();
}

关于 typescript : question mark on array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60457971/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com