大家好,我有数组,我需要执行各种操作,如总和、总计、平均值。所有这三个都已实现,现在我需要找到数组中的最小值和最大值。我被困在下面是代码。
以下是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>
为此使用
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>
将
Math.max
和 Math.min
与展开运算符结合使用。
get max() {
return Math.max(...this.people);
}
get min() {
return Math.min(...this.people);
}
您可以为自己创建一个小帮助器类,它可以为您执行这些操作,并且可以在整个代码中重用
export class MathOps {
array: number[];
constructor(array: number[]) {
this.array = array;
}
sum(): number {
return this.array.reduce((a, b) => a + b, 0);
}
avg(): number {
return this.sum() / this.array.length;
}
max(): number {
return Math.max(...this.array);
}
min(): number {
return Math.min(...this.array);
}
}
const ops = new MathOps([1, 2, 3, 4, 5]);
console.log(ops.avg());
console.log(ops.max());
console.log(ops.min());
console.log(ops.sum());
注:
根据用例,您需要将其扩展为缓存结果...
您可以使用
Array.reduce
和 Math.max()
, Math.min()
来实现此目的。
const people = [1,2,3,4,5];
const max = people.reduce((a, b) => Math.max(a, b)); // 5
const min = people.reduce((a, b) => Math.min(a, b)); // 1
const sum = people.reduce((a, b) => a+b, 0); // 15
您可以在here
找到一个工作示例对于对象数组(最小和最大):
const arr = [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}, {a: -1, b: -2, c: -3}];
const min = Math.min(...arr.map(obj => obj.a + obj.b + obj.c));
const max = Math.max(...arr.map(obj => obj.a + obj.b + obj.c));
const minResult = arr.find(obj => obj.a + obj.b + obj.c == min); // {a: -1, b: -2, c: -3}
const maxResult = arr.find(obj => obj.a + obj.b + obj.c == max); // {a: 4, b: 5, c: 6}
[或]
const arr = [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}, {a: -1, b: -2, c: -3}];
const min = arr.reduce((p,v) => (p.a + p.b + p.c) < (v.a + v.b + v.c) ? p : v); // {a: -1, b: -2, c: -3}
const max = arr.reduce((p,v) => (p.a + p.b + p.c) > (v.a + v.b + v.c) ? p : v); // {a: 4, b: 5, c: 6}