angular - 对象的构造函数数组 - typescript

标签 angular typescript object

我正在使用 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;
}

错误如下:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined

最佳答案

问题是您将 color 属性声明为具有 {one: 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

关于angular - 对象的构造函数数组 - typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48304952/

相关文章:

angular - 创建可重用的 matAutocomplete 指令

angular - 如何停止重命名从 prod build 中生成的文件的 Angular cli

Angular CLI v6 : --no-aot build option equivalent

mysql - 无法使用 OneToMany 关系添加新记录

angular - 是否可以模拟 typescript 装饰器?

python - a = [0] 和 a = [i for i in range(1)] 之间的 sizeof 差异

typescript - Angular2 - browser_adapter.ts 原始异常 : No provider for Location

typescript - 如何组织 TypeScript 接口(interface)

javascript - 如何将对象插入数组?

Javascript 按整数字段对对象进行排序