admin管理员组文章数量:1366451
I am trying to push to an array but it keeps giving me this error:
Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
here is the source where I am simply adding to an array. I take the obsevable from the firestore collection and loop through it. Why is it giving me this error when the array of category objects is right there. categories: Category[];
transactions: Observable<Transaction[]>;
categories: Category[];
private organizeData() {
let category: Category;
this.transactions.forEach(v => {
for (let i = 0; i < v.length; i++) {
category = {name: v[i].category, totalSpent: v[i].amount};
this.categories.push(category);
}
});
}
I am trying to push to an array but it keeps giving me this error:
Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
here is the source where I am simply adding to an array. I take the obsevable from the firestore collection and loop through it. Why is it giving me this error when the array of category objects is right there. categories: Category[];
transactions: Observable<Transaction[]>;
categories: Category[];
private organizeData() {
let category: Category;
this.transactions.forEach(v => {
for (let i = 0; i < v.length; i++) {
category = {name: v[i].category, totalSpent: v[i].amount};
this.categories.push(category);
}
});
}
Share
Improve this question
edited Jun 21, 2018 at 17:10
Frank van Puffelen
600k85 gold badges890 silver badges860 bronze badges
asked Jun 21, 2018 at 15:41
Zach StarnesZach Starnes
3,1989 gold badges42 silver badges66 bronze badges
2 Answers
Reset to default 8categories: Category[]
is just the declaration of an array, you need to actually create a new array and assign it to the field:
categories: Category[] = []
You are not initiating your array categories
so it will return undefined. Try:
categories: Category[] = [];
本文标签: javascriptTypescript undefined is not an object when pushing to arrayStack Overflow
版权声明:本文标题:javascript - Typescript undefined is not an object when pushing to array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743795301a2540316.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论