185
rated 0 times
[
189]
[
4]
/ answers: 1 / hits: 7467
/ 7 Years ago, thu, february 2, 2017, 12:00:00
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?
More From » arrays