Jig*_*try 2 arrays typescript angular angular6
大家好,我有阵列,我需要执行各种操作,如总和,平均值.所有这三个都实现了,现在我需要找到数组中的最小值和最大值.我坚持下面是代码.
以下是TS部分
people: Array<number> = [1, 2, 3, 4, 5];
total: number = 0;
arrayLength: number = this.people.length;
average: number = 0;
sum() {
for (var i in this.people) { this.total += this.people[i]; }
}
ngOnInit() {
this.sum();
this.average = (this.total / this.arrayLength);
}
Run Code Online (Sandbox Code Playgroud)
下面是HTML部分
<span *ngFor="let p of people" style="font-size:18px">{{p}} </span><br><br>
<button >Quantity</button> = {{arrayLength}}<Br><br>
<button >Average</button> = {{average}}<Br><br>
<button >Sum</button> <span *ngIf="sumShow"> = {{total}}</span><Br><br>
Run Code Online (Sandbox Code Playgroud)
reduce为此使用。
sum() {
this.total = this.people.reduce((a, b)=>a + b);
}
ngOnInit() {
this.sum();
this.max = this.people.reduce((a, b)=>Math.max(a, b));
this.min = this.people.reduce((a, b)=>Math.min(a, b));
this.average = (this.total / this.arrayLength);
}
<span *ngFor="let p of people" style="font-size:18px">{{p}} </span><br><br>
<button >Quantity</button> = {{arrayLength}}<Br><br>
<button >Average</button> = {{average}}<Br><br>
<button >Sum</button> <span > = {{total}}</span><Br><br>
<button >Max</button> <span > = {{max}}</span><Br><br>
<button >Min</button> <span > = {{min}}</span><Br><br>
Run Code Online (Sandbox Code Playgroud)
使用Math.max并Math.min与扩展运算符结合使用.
get max() {
return Math.max(...this.people);
}
get min() {
return Math.min(...this.people);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7054 次 |
| 最近记录: |