typescript 如何向数组添加值 - Angular2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37823094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add values to array- Angular2
提问by Aleksandar Milicevic
I made an array like this in angular2, and also I made a form to fill out a table and it works well. But my question is what is the best way to put some values in this array without filling the form, I want some content already in this array.
我在 angular2 中制作了一个这样的数组,并且我制作了一个表格来填写表格,并且效果很好。但我的问题是在不填写表单的情况下将某些值放入此数组的最佳方法是什么,我希望此数组中已有一些内容。
employeeList = new Array<{name:string, bio:string, job:string, salery:string, url:string}>();
回答by Andrei Zhytkevich
Create a class representing your structure:
创建一个表示您的结构的类:
export class User {
name: string;
bio: string;
job: string;
salary: string;
url: string
constructor(_name: string, _bio: string, _job: string, _salary: string, _url: string) {
this.name = _name; this.bio = _bio; this.job = _job; this.salary = _salary; this.url = _url;
}
}
or like this:
或者像这样:
export class User {
constructor(public name: string,
public bio: string,
public job: string,
public salary: string,
public url: string) {
}
}
You array will look like this:
您的阵列将如下所示:
users: User[] = []; // if it's a class member
var users: User[] = []; // if it's a local variable
Add something to array:
添加一些东西到数组:
this.users.push(
new User("Bob", "", "Developer", "100", "github.com");
)