一个javascript数组的总和返回所有数字的字符串连接 [英] Sum of a javascript array returns a string concatenation of all the numbers
问题描述
我正在用ajax获取一个php json_encode对象.我想做的就是对这个数组求和.这是我到目前为止所做的:
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 );
但是结果是:
09.748.529.129.129.119.59.79.89.79.89.79.79.79.79.79.79719.248.59.79 ......
我也尝试过:
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).
我也尝试过:
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).
那么在javascript中对数组求和的正确方法是什么?
So what is the proper way to sum an array in javascript?
推荐答案
您必须使用parseInt
(如果数字是整数),parseFloat
(如果它们是 Floats )或Number
(如果不确定),以将它们明确解释为数字,例如:
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);
这篇关于一个javascript数组的总和返回所有数字的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!