如何将类中的信息写入typescript中的列表?
class UserDeposit {
username: string;
userdeposit: number;
constructor(username: string, userdeposit: number) {
this.username = username;
this.userdeposit = userdeposit;
}
getUsername(): string {
return this.username;
}
getDepositValue(): number {
return this.userdeposit;
}
}
我想创建一个列表,我想存储所有这些信息:
let deposit: UserDeposit[] = [
{ "username": "Test", "deposit": 20 },
{ "username": "Test2", "deposit": 20 },
...........,
];
在我的控制台输出中,我想得到这样的玩家数量和存款总价值(伪代码):
deposit.countUser + " User joined the Jackpot. The total value is " + deposit.totalValue
2 User joined the Jackpot. The total value is 40$
我是TypeScript的新手 有人能帮助我吗?
答案 0 :(得分:0)
你的课很好。
通过这种方式,您可以在列表中添加新元素:
// initialize list:
let deposit: UserDeposit[] = [];
// add new elements
deposit.push(new UserDeposit('test1', 10));
deposit.push(new UserDeposit('test2', 20));
deposit.push(new UserDeposit('test3', 30));
输出结果如下:
console.log('Users: ' + deposit.length + '\nTotal Deposit Value: ' + deposit.reduce((a, b) => a + b.getDepositValue(), 0));
控制台应该打印:
用户:3
总存款价值:60