【问题标题】:Calculate and get sum of an array using ionic angular使用离子角度计算并获取数组的总和
【发布时间】:2021-07-14 12:31:04
【问题描述】:

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

    <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 文件中为答案设置的值是一个整数,我想添加所有答案以获得测验结果。如何在得到总结果后对所有值求和并得到结果,我想给它一个等值的值并将其打印到应用程序。

【问题讨论】:

    标签: arrays angular ionic-framework sum


    【解决方案1】:

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

    只需在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 的值。

    【讨论】:

      【解决方案2】:

      我认为 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多