我在组件中有以下声明:
private years: Array<{
year: string,
colspan: number
}> = [];
应该是years
数组,其中每个条目具有两个属性year
和colspan
。现在,我想使用在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
,该属性在我的{{1}的第一个条目处已针对该对象进行了更改}数组?
答案 0 :(得分:2)
您需要先添加元素,然后才能更改其值
您尝试访问
this.years[0]
但是this.years长度是0
所以您需要这样做
this.years.push({ year: "", colspan: 1});
如果要在数组中添加项目,则需要使用.push()函数。 如果您尝试转到要设置的索引,它将无法正常工作