javascript - 过滤 select 的值以进行部分求和
问题描述
有两个类professor
和student
:
- 教授.ts
export class Professor {
id: number
name: string
}
- 学生.ts
import { Professor } from "./professor"
export class Student {
id: number
name: string
score: number
professor: Professor
}
为了将每个学生相对于他的老师的分数加起来,我做了:
sel: number[] = []
prof: Professor[]
stud: Student[]
totalScore: number
partial: number
var: boolean = false
total() {
const total = this.stud
.filter(c => this.sel.map(m => +m).includes(c.id))
.reduce((a, c) => a + c.score, 0);
this.totalScore = total
this.var = true
}
这是页面的 HTML:
<div name="professors" *ngFor="let p of prof; index as j">
{{ p.name }}
<select name="students{{j}}" [(ngModel)]="sel[j]" class="form-control">
<ng-container *ngFor="let s of stud; index as i">
<option *ngIf="s.professor.id === p.id" [value]="s.id">
{{ s.name }} <p>|</p>
{{ s.score }}
</option>
</ng-container>
</select>
<label></label>
</div>
<button type="submit" (click)="total()"
class="btn btn-primary">Go</button>
<div *ngIf="var">
<p>Total: {{totalScore}}<br>
<!--Partial sum: {{partial}}-->
</p>
</div>
如何对选择进行部分总和,例如假设我有 5 位教授,每位教授有 1 位学生,并且只想添加前 3 位学生的结果。这是堆栈闪电战: https ://stackblitz.com/edit/angular-ivy-sjs7fg?file=src/app/app.component.ts
解决方案
将您的总方法更改为:-
total() {
const total = this.stud
.filter(c => this.sel.map(m => +m).includes(c.id))
.slice(0,3)
.reduce((a, c) => a + c.score, 0);
this.totalScore = total
this.variable = true
}
工作堆栈闪电战:- https://stackblitz.com/edit/angular-ivy-nkxswo?file=src/app/app.component.ts
推荐阅读
- javascript - 无法在 TinyMCE 中上传文件...?
- python - 自动创建未分组条形图的功能
- xml - 从 XML 填充 TreeView 节点和 ChildNodes(特别是 PList)
- c - 指针报告不同值的副本
- axapta - 如何在 D365FO 数据实体中使用 Group By
- tensorflow - 网络摄像头框架到 model.predict_generator - Jupyter Notebook & CV2
- time-series - 时间序列折线图缺少范围工具/缩放
- google-sheets - 使用基于另一个谷歌工作表的查找值创建一个谷歌工作表
- php - 如何使用 asdf 安装 PHP
- cordova - 错误:无法解析配置“:_x86_64DebugApkCopy”的所有依赖项