簡體   English   中英

類型錯誤:無法使用 AngularJS 讀取未定義的屬性“推送”

[英]TypeError: Cannot read property 'push' of undefined with AngularJS

我正在嘗試將我的數據推送到此CompareArray但出現以下錯誤:

TypeError: Cannot read property 'push' of undefined
    at Object.addResult (src\services\CompareService.js:22)

代碼:

this.addResult = function (type, result) {
    this[type.toLowerCase() + 'CompareArray'].push(result);
    this.checkToDisplayLinks(type);
    this.checkToDisableCheckboxes(type);
};

在推送任何內容之前檢查它是否未定義和初始化

if(this[type.toLowerCase() + 'CompareArray']){
 this[type.toLowerCase() +  'CompareArray'].push(result);
}
else
{
   this[type.toLowerCase() +  'CompareArray'] = [result];
}

如果你仔細觀察,錯誤是自我描述的。

Cannot read property 'push' of undefined at Object.addResult 

addResult 是你的方法。 你在“推”

this[type.toLowerCase() + 'CompareArray'].push(result);

它說 - 未定義的“推送”。 意思是

this[type.toLowerCase() + 'CompareArray'] 

未定義。 Push 是一種僅適用於數組的方法。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM