我正在使用typescript
来编写Angular2代码。我有这个对象:
export class Car{
name: String;
door: {
position: String;
id: Number;
};
}
我按照以下步骤初始化了对象:
constructor() {
this.door= new Door();
}
export class Door{
position: String;
ID: Number
}
它完美无缺。当我尝试初始化一个对象数组时,我的问题就开始了
export class Car{
name: String;
door: {
position: String;
id: Number;
};
color: {
one: String;
two: String;
}[]
}
我尝试做同样的事情 的被修改
constructor() {
for (var i = 0; i < 10; i++) {
this.color.push(new Color);
}
this.door= new Door();
}
export class Color{
one: String;
two: String;
}
错误如下:
错误错误:未捕获(在承诺中):TypeError:无法读取属性&#39; push&#39;未定义的 TypeError:无法读取属性&#39; push&#39;未定义的
答案 0 :(得分:2)
问题是您使用color
类型的单个项目将{one: string; two: string}
属性声明为元组
要初始化元组,您可以使用
this.color= [new Color()];
或者,如果您要声明可以使用的类型数组:
color: {
one: String;
two: String;
}[]
并用空数组初始化它:
this.color= [];
// Push 10 elements in the array, you can replace 10 with how many elements you need.
for(let i = 0; i< 10; i++) this.color.push(new Color());
有关元组here
的更多信息