0

In my project I have a select where choosing the type, changes the total of the function. The problem is that if I don't select all three type first, the total in console.log gives me a NaN. How can I still have the total without needing the result of the other two types?

type: number = 0

calcTotal() {
    this.variabileIntervento.forEach(t => {
      t.totale = []
      for (const i in t.varianti) {
        this.modCos = t.modicitaDiCosto[i] * this.ponderazione[0]
        this.effic = t.efficacia[i] * this.ponderazione[1]
        if(this.type == 1) {
          this.supInton = t.supIntonacate[i] * this.ponderazione[2]
        } 
        else if(this.type == 2) {
          this.supEv = t.supEvIi[i] * this.ponderazione[2]
        } 
        else if(this.type == 3) {
          this.supIv = t.supIvEi[i] * this.ponderazione[2]
        }
        this.revers = t.reversibilita[i] * this.ponderazione[3]
        this.semplCant = t.semplicitaDiCantiere[i] * this.ponderazione[4]
        this.esigIngom = t.esiguitaDiIngombro[i] * this.ponderazione[5]
        t.totale.push(this.modCos + this.effic + this.supInton + this.supEv + this.supIv + this.revers + this.semplCant + this.esigIngom)
      }
      console.log("Total: ", t.totale);
    })
  }
  • 1
    If you multiply `undefined` by a number you get `NaN`. I'm assuming that one of your array accesses doesn't contain that element and thus returns `undefined` – JensV Feb 08 '21 at 12:14
  • Does this answer your question? [When should I use ?? (nullish coalescing) vs || (logical OR)?](https://stackoverflow.com/questions/61480993/when-should-i-use-nullish-coalescing-vs-logical-or) – ikiK Feb 08 '21 at 12:14
  • I recommend stepping through your code with your debugger, where you can see which arrays contain which elements – JensV Feb 08 '21 at 12:15
  • First define every element from `t.totale.push` to be 0: `this.modCos = 0; this.effic = 0`... And when retrieving information make sure you cast to int/float – Justinas Feb 08 '21 at 12:15

0 Answers0