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

jo3rn
1,4491 gold badge16 silver badges30 bronze badges
asked Nov 25, 2009 at 18:55

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.

answered Nov 25, 2009 at 18:57

Comments

4
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
Levi
1,7721 gold badge13 silver badges11 bronze badges
answered Oct 8, 2013 at 5:09

Comments

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];
}
answered Nov 25, 2009 at 18:58

Comments

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;
}
answered Nov 25, 2009 at 18:58

4 Comments

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

Use parseInt or parseFloat (for floating point)

var total = 0;
for (i=0; i<10; i++)
 total+=parseInt(myArray[i]);
abyx
73.4k19 gold badges99 silver badges121 bronze badges
answered Nov 25, 2009 at 18:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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