我有一个对象数组,当我尝试访问它时,会出现以下错误:
TypeError: 无法设置未定义的属性 'ID'
我的代码如下:
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos].ID = "test";
}
}
作为对象的一部分
export class Piece{
ID: string;
doors: string;
}
我在HTML中使用一个有效的位置调用了test(pos)
。
我猜我试图访问一个未初始化的数组的第X个位置。我该怎么做?是否可以创建一个构造函数?
pieces: Piece[] = [];
? - kshetline