[英]How to initialize an array in angular2 and typescript
Why does this happen in Angular2 and 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.
How on do I initialize an array? 如何初始化数组?
You can use this construct: 你可以使用这个结构:
export class AppComponent {
title:string;
myHero:string;
heroes: any[];
constructor() {
this.title = 'Tour of Heros';
this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
this.myHero = this.heroes[0];
}
}
你可以像这样创建和初始化任何对象的数组。
hero:Hero[]=[];
Class definitions should be like : 类定义应该是这样的:
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
Source: https://www.typescriptlang.org/docs/handbook/classes.html 资料来源: https : //www.typescriptlang.org/docs/handbook/classes.html
I don't fully understand what you really mean by initializing an array? 我不完全理解初始化数组的真正含义?
Here's an example: 这是一个例子:
class Environment {
// you can declare private, public and protected variables in constructor signature
constructor(
private id: string,
private name: string
) {
alert( this.id );
}
}
let environments = new Environment('a','b');
// creating and initializing array of Environment objects
let envArr: Array<Environment> = [
new Environment('c','v'),
new Environment('c','v'),
new Environment('g','g'),
new Environment('3','e')
];
Try it here : https://www.typescriptlang.org/play/index.html 在这里试试: https : //www.typescriptlang.org/play/index.html
In order to make more concise you can declare constructor parameters as public
which automatically create properties with same names and these properties are available via this
: 为了使更简洁,你可以声明构造函数的参数作为
public
可自动创建具有相同的名称属性和这些属性通过提供this
:
export class Environment {
constructor(public id:number, public name:string) {}
getProperties() {
return `${this.id} : ${this.name}`;
}
}
let serverEnv = new Environment(80, 'port');
console.log(serverEnv);
---result---
// Environment { id: 80, name: 'port' }
hi @JackSlayer94 please find the below example to understand how to make an array of size 5. 您好@ 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()); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.