Sum of a javascript array returns a string concate

2020-03-31 09:11发布

I'm having a php json_encode object fetched by ajax. whet I want to do is to sum this array. Here's what I did so far:

var json = $.parseJSON(data);
var tot = new Array();
for (var i = 0; i < json.length; ++i) {
   tot.push(json[i].final_total);
   $('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}

Now I want to sum this array. I tried this:

var sum = tot.reduce(function(pv, cv) { return pv + cv; }, 0);
$("#total").html( sum );

But the result is:

09.748.529.129.129.119.59.79.89.79.89.79.79.79.79.79.79719.248.59.79 ......

I also tried:

myFunction(tot); 

function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("total").innerHTML = item.reduce(getSum);
}

But I got the same result above (Numbers written next to each other).

I also tried this:

var tot = 0;
for (var i = 0; i < json.length; ++i) {
   tot += json[i].final_total);
   $('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
$("#total").html( tot );

But I got the same result above (Numbers written next to each other).

So what is the proper way to sum an array in javascript?

3条回答
够拽才男人
2楼-- · 2020-03-31 09:18

Array elements are strings, in order to properly add them, they have to be casted to integer:

var sum = tot.reduce(function(a, b) {
  return parseFloat(a) + parseFloat(b);
}, 0);

Taken from MDN:

the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

The is a common issue caused by + operator used for both string concatenation and addition. Issue is best described with following example:

var result = '1' + 3 + 3 + 7 //result is '1337'

Edit: @Pointy - Nice catch, thanks! :)

查看更多
再贱就再见
3楼-- · 2020-03-31 09:21

you will need to use a parse int because its concatenating the sting instead of adding integers

var sum = tot.reduce(function(pv, cv) { return parseInt(pv) + parseInt(cv); }, 0);

parseInt

查看更多
走好不送
4楼-- · 2020-03-31 09:31

You have to use parseInt (if the numbers are Integers), parseFloat (if they are Floats) or Number (if not sure) to explicitly interpret them as numbers like:

sum = tot.reduce((a, n) => (a + Number(n)), 0);
查看更多
登录 后发表回答