在TypeScript中循环自定义对象数组

时间:2017-04-12 14:16:28

标签: arrays typescript

我开始玩TypeScript了。我创建了两个类(Student和Listview)。我试图用我创建的学生对象循环数组,但不知何故它不起作用。

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

class Listview {
    items: Array<Student>;
    constructor(public item_list: Array<Student>) {}

    log(): void {
        var items = this.items;
        for(var i=0; i<items.length; i++) {
          console.log(items[i]);
        }
    }

}

var list = new Listview(
    [new Student("Jane", "M.", "User"),
    new Student("Hans", "M.", "Muster"),
    new Student("Fritz", "B.", "Muster")]
);
list.log();

我在控制台中收到此警告:

console error

如何访问数组以读取每个学生对象的属性?

问候 Orkun

1 个答案:

答案 0 :(得分:2)

您的ListView应如下所示,以便正确初始化items

class Listview {
    constructor(public items: Array<Student>) {}

    log(): void {
        var items = this.items;
        for(var i=0; i<items.length; i++) {
          console.log(items[i]);
        }
    }
}