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数组的总和返回所有数字的字符串连接
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
