我在角11中创建了名测试接口
export interface Test {
id:number;
name:string;
}然后导出接口并创建其名为ProvinceAllStudent的数组。
import { Test } from './../../../student/Models/test';
import { Component, OnInit } from '@angular/core';
import { Province } from 'src/app/student/Models/Province.model';
@Component({
selector: 'app-general-statistic',
templateUrl: './general-statistic.component.html',
styleUrls: ['./general-statistic.component.css']
})
export class GeneralStatisticComponent implements OnInit {
Provinces:any[];
ProvinceAllStudent:Test[]=[];
constructor(
) { }
ngOnInit(): void {
this.CalculateProvinceStudents()
}
CalculateProvinceStudents()
{
for(let j=0;j<5;j++)
{
this.ProvinceAllStudent[j].id=j;
this.ProvinceAllStudent[j].name='A';
}
}
}当我运行应用程序时,我得到了错误。
GeneralStatisticComponent.CalculateProvinceStudents (general-statistic.component.ts:23)
core.js:6210 ERROR TypeError:无法设置未定义的属性(设置'id')
发布于 2021-09-18 20:16:59
因为this.ProvinceAllStudent[j]是undefined,所以您尝试给它的一个属性赋值。(undefined没有id和name属性,因此会引发异常。)
我建议使用数组的push方法。例如
for (let j = 0; j < 5; j++) {
this.ProvinceAllStudent.push({ id: j, name: 'A' });
}或者作为替代方案,您可以通过这种方式按索引添加元素:
for(let j = 0; j < 5; j++) {
this.ProvinceAllStudent[j] = {id: j, name: 'A'};
}发布于 2021-09-18 20:14:04
在数组中修改对象之前,需要先创建对象。
this.ProvinceAllStudent.push({
id: j,
name: 'A'
})https://stackoverflow.com/questions/69238068
复制相似问题