如何处理Angular 5中的未定义对象属性
2018-05-16
7247
我尝试通过将对象属性值设置为空字符串来修复未定义的错误,但仍然出现如下错误:
ERROR TypeError: Cannot read property 'notes' of undefined
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>
我参考了这个答案,但没有用: 如何在 javascript 中处理“未定义”
1个回答
如果 notes 数组元素 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”变量,而不是实际的数组项。
假设我有一个 cars 数组:
if (!cars[0]) {
cars[0] = <Car>{};
cars[0].color = "blue";
}
David Anthony Acosta
2018-05-16