循环遍历对象数组,计算每年的年收入,并使用Angular 2将其显示在表中的步骤如下:
const incomeData = [
{ year: 2019, income: 10000 },
{ year: 2020, income: 15000 },
{ year: 2021, income: 20000 }
];
<table>
<thead>
<tr>
<th>年份</th>
<th>年收入</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of incomeData">
<td>{{ data.year }}</td>
<td>{{ data.income }}</td>
</tr>
</tbody>
</table>
import { Component } from '@angular/core';
@Component({
selector: 'app-income-table',
templateUrl: './income-table.component.html',
styleUrls: ['./income-table.component.css']
})
export class IncomeTableComponent {
incomeData = [
{ year: 2019, income: 10000 },
{ year: 2020, income: 15000 },
{ year: 2021, income: 20000 }
];
calculateYearlyIncome(): number {
return this.incomeData.reduce((total, data) => total + data.income, 0);
}
}
<p>总收入: {{ calculateYearlyIncome() }}</p>
这样,循环遍历对象数组,计算每年的年收入,并使用Angular 2将其显示在表中的功能就完成了。
领取专属 10元无门槛券
手把手带您无忧上云