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/

2
  • 1
    Typo: Remove the semicolon after the for(...); <---. That's an empty statement, which became the body of the loop. Commented Oct 8, 2016 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. Commented Oct 8, 2016 at 15:53

1 Answer 1

5

You could use brackets

  var total = 0;

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

      total  += totalPrice[i];

   }
   document.getElementById("displayPrice").innerHTML = total;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.