簡體   English   中英

無法設置未定義TypeScript-Array的屬性“ year”

[英]Cannot set a property “year” of undefined TypeScript-Array

我的組件中有以下聲明:

private years: Array<{
    year: string,
    colspan: number
  }> = [];

這應該是一個years -陣列,其中每個條目有兩個屬性yearcolspan 現在,我想使用在ngOnInit調用的以下方法來修改此變量:

fillYearsArray = () => {
    var currentIndex : number = 1;
    //fill the first entry and do not change it afterwards, error occurs here
    this.years[0].year = "";
    this.years[0].colspan= 1;

    this.items.forEach( (item) => {
      //if the first entry.year is empty fill it with the year of the current object
      if (this.years[currentIndex].year) {
      //if it is already set and the years equal enlarge colspan  
      //otherwise go to the next entry with the "new" year
      if (this.years[currentIndex].year === String(item.year)) {
          this.years[currentIndex].colspan += this.columnKeys.length;
        } else {
          currentIndex++;
          this.years[currentIndex].year = String(item.year);
          this.years[currentIndex].colspan = this.columnKeys.length;
        }
      } else {
        this.years[currentIndex].year = String(item.year);
      }
    });
  }

但是當運行ng serve我得到以下輸出:

AppComponent.html:1 ERROR TypeError: Cannot set property 'year' of undefined
    at TabularComponent.fillYearsArray (tabular.component.ts:27)
    at TabularComponent.push../src/app/tabular/tabular.component.ts.TabularComponent.ngOnInit (tabular.component.ts:22)
    at checkAndUpdateDirectiveInline (core.js:18537)
    at checkAndUpdateNodeInline (core.js:19801)
    at checkAndUpdateNode (core.js:19763)
    at debugCheckAndUpdateNode (core.js:20397)
    at debugCheckDirectivesFn (core.js:20357)
    at Object.eval [as updateDirectives] (AppComponent.html:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:20349)
    at checkAndUpdateView (core.js:19745)

因此,看起來數組中的第一個對象是未定義的,但TS不應該知道,它的屬性year在我的years的第一個條目-array中更改了嗎?

您需要先添加元素,然后才能更改其值

您嘗試訪問

this.years[0]

但是this.years長度是0

所以你需要這樣

this.years.push({ year: "", colspan: 1});

如果要在數組中添加項目,則需要使用.push()函數。 如果您嘗試轉到要設置的索引,它將無法正常工作

暫無
暫無

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

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