首页 > 解决方案 > 如何使用 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”错误,我应该怎么做才能在按钮点击时获得特定学生的平均值。

标签: javascriptjsonangulartypescript

解决方案


试试这样:

.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>

工作演示


推荐阅读