tags:

views:

75

answers:

4

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

Like this:

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

With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10 and myArr[2] = 10 then TOTAL will be 1010 instead of 20.

How should I write what I want ?

Thanks

+4  A: 

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.

CMS
LOL, that means that `lol -=- lmao` is valid java script? :)
abyx
+1  A: 

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;
}
Pim Jager
It's not wise to leave off the radix parameter
Greg
Dammit, your absolutly right, was just to eager to get my answer out there. added it.
Pim Jager
Really? Why isn't it wise? In Java it defaults to 10. Is it different in javascript?
abyx
@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...
CMS
+2  A: 

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];
}
Greg
A: 

Use parseInt or parseFloat (for floating point)

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