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
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
Share Improve this question edited Mar 26, 2024 at 15:04 jo3rn 1,4211 gold badge15 silver badges30 bronze badges asked Nov 25, 2009 at 18:55 user188962user1889625 Answers
Reset to default 7Sounds 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 mon way to make sure you are adding up numbers, not concatenating strings.
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
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];
}
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;
}
Use parseInt
or parseFloat
(for floating point)
var total = 0;
for (i=0; i<10; i++)
total+=parseInt(myArray[i]);