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.
Use parseInt()
function javascript
total=parseInt(total)+parseInt(data[i]);
Try with parseInt:
total=total+parseInt(data[i]);
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.
Try this one:
var total = 0;
for (var i = 0; i < someArray.length; i++) {
total += someArray[i] << 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".