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.
f
Use parseInt() function javascript
total=parseInt(total)+parseInt(data[i]);
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".
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;
}