1

I'm trying to find a way to sum all the numbers that have been added to an array. I believe this should work:

   var total = 0;

   for (var i  = 0; i < totalPrice.length; i++);

   total  += totalPrice[i];
   document.getElementById("displayPrice").innerHTML = total;

But total comes out as a NaN.

This is an example of my code in JSFiddle, if you add the item twice the value gets pushed into the array, what am I doing wrong with the for loop?

https://jsfiddle.net/bgv5s9re/2/

Sergi
  • 1,192
  • 3
  • 19
  • 37
  • 1
    Typo: Remove the semicolon after the `for(...); <---`. That's an empty statement, which became the body of the loop. –  Oct 08 '16 at 15:51
  • You're welcome. And just FYI, you get `NaN` because `i` is out of bounds, so you're doing `total += undefined`, since out of bounds array access produces the `undefined` value. –  Oct 08 '16 at 15:53

1 Answers1

5

You could use brackets

  var total = 0;

   for (var i  = 0; i < totalPrice.length; i++){

      total  += totalPrice[i];

   }
   document.getElementById("displayPrice").innerHTML = total;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107