javascript数组的总和返回所有数字的字符串连接 [英] Sum of a javascript array returns a string concatenation of all the numbers

查看:23
本文介绍了javascript数组的总和返回所有数字的字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 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(如果数字是Integers),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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆