0

Hi I am trying to sum an array on Javascript with the following codes.

var data[]: 
var total=0;
data.push[x]; // x is numbers which are produced dynamically. 
for(var i=0, n=data.length; i < n; i++) 
 { 
  total=total+data[i];
 }
alert(total)

for example if x values are are respectively 5,11,16,7. It shows the total value as 511167 not sum the values 5+11+16+7=39 Do you have any idea why it results like that? Thanks.

3
  • Are you sure your x is actually a list of int? Commented May 28, 2013 at 12:27
  • Why ? Because the "+" operator interacts like a concat... Commented May 28, 2013 at 12:28
  • total = total + +data[i] Commented May 28, 2013 at 13:40

5 Answers 5

1

Use parseInt() function javascript

total=parseInt(total)+parseInt(data[i]);
Sign up to request clarification or add additional context in comments.

1 Comment

You can write total += parseInt(data[i]);, if total is initialized as an int it will remain an int
1

Try with parseInt:

total=total+parseInt(data[i]);

Comments

1

Simply whip a unary + before data[i] to convert the string values to numeric values:

total = total + (+data[i]);

Even better, use += instead of total=total+...:

total += +data[i];

JSFiddle demo.

Comments

0

Try this one:

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

Comments

0

Use parseInt() javascript function....

total = total + parseInt(data[i]);

This looks the 'x' which you mention come dynamically has a string type. Just check the "typeof x".

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.