[英]Angular 7.2.5 + Typescript 3.2.4: Cannot read property 'aaa' of undefined
我有以下幾行代碼:
if ((this.axes.x && this.axes.x.property === 'run_number') ||
(this.axes.y && this.axes.y.property === 'run_number')) {
this.buildLineGraph(this.axes.y.property === 'run_number');
} else {
this.buildScatterGraph();
}
大部分時間運行都沒有問題,但是如果鏈中的任何元素不時會失敗:
this.axes.x.property
this.axes.y.property
給出錯誤:
無法讀取未定義的屬性“ aaa”
aaa是未定義的元素:axes,x,y等。
如何檢查每個可能的未定義元素? 我是否需要一長串嵌套的if語句?
我正在回答自己的問題,但隨時可以將更好,更優雅的解決方案作為單獨的答案發布,以便我投票贊成。
if (this && this.axes && this.axes.x && this.axes.y && this.axes.x.property && this.axes.y.property) {
if ((this.axes.x && this.axes.x.property === 'run_number') ||
(this.axes.y && this.axes.y.property === 'run_number')) {
this.buildLineGraph(this.axes.y.property === 'run_number');
} else {
this.buildScatterGraph();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.