Sum of a javascript array returns a string concatenation of all the numbers(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数组的总和返回所有数字的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javascript数组的总和返回所有数字的字符串连接


- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01