查找Array Angular和Typescript中的最小和最大元素

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)

Kri*_*ore 7

reduce为此使用。

Stackblitz 上的演示

  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)


Tom*_*ula 6

使用Math.maxMath.min与扩展运算符结合使用.

get max() {
  return Math.max(...this.people);
}

get min() {
  return Math.min(...this.people);
}
Run Code Online (Sandbox Code Playgroud)