简体   繁体   中英

Typescript undefined is not an object when pushing to array

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);
      }
    });
  }

categories: Category[]只是数组的声明,您实际上需要创建一个新数组并将其分配给字段:

categories: Category[] = []

You are not initiating your array categories so it will return undefined. Try:

categories: Category[] = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM