你好,我有数组,我需要执行各种操作,如求和、总计、平均值。所有这 3 个都实现了,现在我需要找到数组中的最小值和最大值。我被困在下面是代码。
下面是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);
}
下面是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>
最佳答案
将Math.max
和Math.min
与展开运算符结合使用。
get max() {
return Math.max(...this.people);
}
get min() {
return Math.min(...this.people);
}
关于arrays - 在 Array Angular 和 Typescript 中查找最小和最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51840141/