如何在 angular2 和 typescript 中初始化数组

新手上路,请多包涵

为什么在 Angular2 和 Typescript 中会发生这种情况?

 export class Environment {
    constructor(
      id: string,
      name: string
    ) { }
}

 environments = new Environment('a','b');

app/environments/environment-form.component.ts(16,19): error TS2346: Supplied parameters do not match any signature of call target.

如何初始化数组?

原文由 Tampa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 922
2 个回答

类定义应该是这样的:

 export class Environment {
    cId:string;
    cName:string;

    constructor( id: string, name: string ) {
        this.cId = id;
        this.cName = name;
    }

    getMyFields(){
        return this.cId + " " + this.cName;
    }
}

 var environments = new Environment('a','b');
 console.log(environments.getMyFields()); // will print a b

来源: https ://www.typescriptlang.org/docs/handbook/classes.html

原文由 eko 发布,翻译遵循 CC BY-SA 3.0 许可协议

嗨@JackSlayer94 请找到以下示例以了解如何制作大小为 5 的数组。

 class Hero {
    name: string;
    constructor(text: string) {
        this.name = text;
    }

    display() {
        return "Hello, " + this.name;
    }

}

let heros:Hero[] = new Array(5);
for (let i = 0; i < 5; i++){
    heros[i] = new Hero("Name: " + i);
}

for (let i = 0; i < 5; i++){
    console.log(heros[i].display());
}

原文由 Mahesh Yadav 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进