Summing array on Javascript

2020-05-09 01:30发布

问题:

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.

回答1:

Use parseInt() function javascript

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


回答2:

Try with parseInt:

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


回答3:

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.



回答4:

Try this one:

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


回答5:

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".