我尝试通过将object属性值设置为空字符串来修复未定义的错误,但仍然会出现如下所述的错误:
错误类型错误:无法读取属性'注释'未定义的
TS
let notes;
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
notes = '';
} else {
notes = manufacturer_field.manufacturer_guidelines[0].notes;
}
HTML
<p *ngIf="field.notes?.length">{{field.notes}}</p>
我提到了这个答案,但那不起作用:How to handle 'undefined' in javascript
答案 0 :(得分:1)
如果数组元素0未定义,则会抛出错误:
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
因为您正在检查属性是否未定义,而实际未定义的是.manufacturer_guidelines [0]项目。
相反,你可以这样做:
if (!manufacturer_field.manufacturer_guidelines[0]){
manufacturer_field.manufacturer_guidelines[0] = (assign it whatever value belong to this sort of item, and then once you know it is valid, then add notes)
}
此外,您将字符串分配给“notes”变量,而不是实际的数组项。
所以我想说我有一个汽车阵列:
if (!cars[0]) {
cars[0] = <Car>{};
cars[0].color = "blue";
}