javascript - 如何使用 json 数据计算 Angular 中的平均值
问题描述
import {
Component,
OnInit
} from "@angular/core";
import {
MarkService
} from "../app/services/marks.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
title = "my-test";
public students = [];
allStudents: any = [];
average: any = [];
constructor(private _marksService: MarkService) {}
ngOnInit() {
this._marksService.getMarks().subscribe(data => (this.students = data));
}
calHandle(i) {
var data = this.students;
this.average = Object.values(data).reduce(
(avg, {
values
}, _, {
length
}) => avg + values / length,
0
);
}
}
<table border="1">
<tr>
<th>Name</th>
<th>Jan</th>
<th>Feb</th>
<th>March</th>
<th>April</th>
<th>action</th>
<th>Average</th>
<!-- </tr> -->
<tbody *ngFor="let item of students; let i = index;">
<tr>
<td>{{item.name}}</td>
<td>{{item.jan}}</td>
<td>{{item.feb}}</td>
<td>{{item.march}}</td>
<td>{{item.April}}</td>
<td><button (click)="calHandle(i)">calculate</button></td>
<td>{{average}}</td>
</tr>
</tbody>
</table>
<!--
json data
[
{"name": "josh", "jan":20,"feb":32, "march":"50", "April":45},
{"name": "peter", "jan":20,"feb":32, "march":"50", "April":45},
{"name": "gorge", "jan":20,"feb":32, "march":"50", "April":45}
]
-->
以上是我用于计算学生点击事件平均值的片段,但每当我点击“计算”按钮时,我得到的结果是“NaN”,所以我有点不确定如何只提供数字值来防止“NaN”错误,我应该怎么做才能在按钮点击时获得特定学生的平均值。
解决方案
试试这样:
.ts
calHandle(i: number) {
var sum = 0;
var keys = Object.keys(this.students[i]);
keys.forEach(key => {
if (key != "name") {
sum += Number(this.students[i][key]);
}
});
this.students[i].average = sum / (keys.length - 1);
}
.html
<table border="1">
<tr>
<th>Name</th>
<th>Jan</th>
<th>Feb</th>
<th>March</th>
<th>April</th>
<th>action</th>
<th>Average</th>
</tr>
<tbody *ngFor="let item of students; let i = index;">
<tr>
<td>{{item.name}}</td>
<td>{{item.jan}}</td>
<td>{{item.feb}}</td>
<td>{{item.march}}</td>
<td>{{item.April}}</td>
<td><button (click)="calHandle(i)">calculate</button></td>
<td>{{item.average}}</td>
</tr>
</tbody>
</table>
推荐阅读
- reactjs - UseState 随机返回数据
- xamarin.ios - Xamarin IOS 需要重定向到 BB Access 以进行 OpenID 连接
- javascript - Java 脚本适用于数字但错误 80020101 与变量...为什么?
- powershell - Powershell 中的实时 TCP 接收器
- c++ - C++。类中指针数组的赋值运算符
- php - 使用 php(共享服务器)实现 Oauth 1.0a
- azure-devops - 分支策略“在最后一次迭代中至少需要一个批准”的含义不清楚
- python - AnalysisException:Sparksql - SUM with CASE WHEN
- android - 在 googleMap Activity 中显示 Toast
- python - 有没有办法使用 sklearn TF-IDF 模型来解决单词类比问题?