使用 ionic angular 计算并获取数组的总和

Calculate and get sum of an array using ionic angular

我正在尝试获取数组中所有值的总和,但我不知道该怎么做。这是我的一组代码。

    <ion-content>
    <ion-card *ngFor="let question of questions">
    <ion-card-header>
      <ion-card-title>
        <h4>{{question.title}}</h4>
      </ion-card-title>
    </ion-card-header>
    <ion-card-content>
      <ion-text>
        <h6>Rating:</h6>
      </ion-text>
      <div margin-vertical text-center>
            <ion-radio-group [(ngModel)]="question.answer">
              <ion-item>
                <ion-radio value=0></ion-radio>
                <ion-label> Not at all</ion-label>
              </ion-item>
              <ion-item>
                <ion-radio value=2></ion-radio>
                <ion-label>For some of the time</ion-label>
              </ion-item>
              <ion-item>
                <ion-radio value=4></ion-radio>
                <ion-label>For most of the time</ion-label>
              </ion-item>
              <ion-item>
                <ion-radio value=5></ion-radio>
                <ion-label>For all of the time</ion-label>
              </ion-item>
            </ion-radio-group>
      </div>
    </ion-card-content>
  </ion-card>
  <div margin-vertical text-center>
    <ion-button (click)='getQuestionResults()'>SUBMIT</ion-button>
  </div>
</ion-content>

这里是 ts 文件。

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

export interface question {
title: string;
answer: number;
}
@Component({
selector: 'app-evaluation',
templateUrl: './evaluation.page.html',
styleUrls: ['./evaluation.page.scss'],
})
export class EvaluationPage implements OnInit {

questions: question[] = [];

constructor(private route: Router) { }

home(){
  this.route.navigate(['/home']);
}
Result(){
  this.route.navigate(['/result']);
}

ngOnInit() {
  // Questions
  for(let i = 1; i <= 1; i++) {
    this.questions.push({ title: `Little interest or pleasure in doing things`, answer: 
undefined });
    this.questions.push({ title: `Feeling down, depressed, or hopeless`, answer: undefined });
    this.questions.push({ title: `Trouble falling or staying asleep, or sleeping too much`, 
answer: undefined });
    this.questions.push({ title: `Feeling tired or having little energy`, answer: undefined });
    this.questions.push({ title: `Often has difficulty organizing tasks or activities`, 
answer: undefined });
    this.questions.push({ title: `Trouble concentrating on things, such as reading the 
newspaper or watching television`, answer: undefined });
    this.questions.push({ title: `Feeling bad about yourself — or that you are a failure or 
have let yourself or your family down`, answer: undefined });
  
    }
  }
  getQuestionResults() {
    console.log(this.questions);
  }

这是它在控制台中的样子,我在 HTML 文件上设置的答案值是一个整数,我想添加所有答案以获得测验结果。得到总结果后如何求和所有值并得到结果我想给它一个等价的值并打印到应用程序。

我认为 Array.reduce 可以解决您的问题。参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

let initialValue = 0;
let sum = this.questions?.reduce(function (accumulator, currentValue) {
    return currentValue?.answer ? accumulator + +currentValue.answer : accumulator;
}, initialValue)

看来,你还缺乏一些基本的编程知识。无论如何,您可以使用以下选项之一:

只需在for周期求和:

let sumA = 0;
for (const q of this.questions) {
    sumA += Number(q.answer || 0);
}

或使用reduce(或mapreduce):

const sumB = this.questions
    .map(q => Number(q.answer || 0))
    .reduce((a, b) => a+b, 0);

你应该记住,你可以从你的 HTML 中得到 string 值,尽管你有类型声明。您需要将您的值转换为 number.

另外,这个值可以是undefinedvalue || 0 可以帮助处理总计 undefined 个值。