我目前正在制作预算应用。我可以通过价格属性添加一系列费用。它是由expense.model.ts构建的。我正在尝试访问Typescript中的price属性。我已经可以使用ngFor循环在HTML上访问它了。有没有一种方法可以在TypeScript中使用for循环?
expenses.service.ts
import { Injectable } from '@angular/core';
import { Expense } from '../expenses-list/expense/expense.model';
@Injectable({
providedIn: 'root'
})
export class ExpensesService {
expenses: Expense [] = [
new Expense('car payment', 350) // price
];
constructor() { }
onAddExpenseToExpenses(expense: Expense) {
this.expenses.push(expense);
}
// EXAMPLE //
onCalculate() {
// get prices from listed items
// add all the prices
// subtract income from sum of prices
}
对不起,如果我不清楚。我刚刚开始使用Angular 6。
感谢您的帮助! =)
这是我的费用模型
export class Expense {
private item: string;
private price: number;
constructor(item: string, price: number) {
this.item = item;
this.price = price;
}
}
答案 0 :(得分:0)
没有类型和接口,TypeScript和JavaScript几乎相同。您应该学习和参考JS文档
有很多处理循环的方法:
针对:
let sumPrices = 0;
for (let i = 0; i < this.expenses; i++) {
sumPrices += this.expenses[i].price;
}
对于...的...
let sumPrices = 0;
for (const o of this.expenses) {
sumPrices += o.price;
}
阵列图:
// get prices from listed items
// add all the prices
const sumPrices = this.expenses.reduce((acc, o) => acc + o.price, 0);
答案 1 :(得分:0)
您只需在打字稿中使用for循环
定义这样的费用
expenses: Array<Expense>
在构造函数中,请在下面编写代码
this.expenses = new Array<Expense>()
let x = new Expense('car payment', 350);
this.expenses.add(x);
//or
this.expenses.push(x);
在onCalculate之后,写这个
let sum = 0
for (let item of expenses) {
sum += item.Price;
}
有关typescriptlang网站上循环研究Iterators and Generators的更多信息