1

I am NOT talking about concatenating elements together, but adding their values to another separate variable.

Like this:

var TOTAL = 0;
for (i=0; i<myArray.length; i++) {
    TOTAL += myArray[i];
}

With this code, TOTAL doesn't add mathematically element values together, but it concatenates them next to each other, so if myArray[0] = "10" and myArray[1] = "10" then TOTAL will be "01010" instead of 20.

How should I write what I want?

Thanks

5 Answers 5

7

Sounds like your array elements are Strings, try to convert them to Number when adding:

var total = 0;
for (var i=0; i<10; i++){
  total += +myArray[i];
}

Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.

0
4
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
2

A quick way is to use the unary plus operator to make them numeric:

var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
    TOTAL += +myArray[i];
}
1

Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)

var total = 0;
for(i=0; i<myArray.length; i++){
  var number = parseInt(myArray[i], 10);
  total += number;
}
4
  • 1
    It's not wise to leave off the radix parameter
    – Greg
    Commented Nov 25, 2009 at 18:59
  • Dammit, your absolutly right, was just to eager to get my answer out there. added it.
    – Pim Jager
    Commented Nov 25, 2009 at 19:01
  • Really? Why isn't it wise? In Java it defaults to 10. Is it different in javascript?
    – abyx
    Commented Nov 25, 2009 at 19:25
  • 1
    @abyx, if you don't use the radix argument. it will depend on the string, '0xFF' will be parsed to 255, '010' to 8, and so on... Commented Nov 25, 2009 at 19:32
0

Use parseInt or parseFloat (for floating point)

var total = 0;
for (i=0; i<10; i++)
 total+=parseInt(myArray[i]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.