我正在尝试获取对象数组中的总订单价格(以美元计)并总计总和。而不是对数组求和,而是将顺序总和连接起来。如何强制添加而不是连接?
<body>
<p id=sales></p>
<script>
var sales, i, x = "";
sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]}
for (i in sales.orders) {
x += sales.orders[i].total_price_usd + ', ';
}
var numbers = [x];
function getSum(total, num) {
return parseFloat(total) + parseFloat(num);
}
document.getElementById('sales').innerHTML = '$' + numbers.reduce(getSum);
</script>
</body>
答案 0 :(得分:1)
此行不会创建数字数组:
var numbers = [x];
它只是创建一个包含一个元素,一个字符串的数组,就像你写的那样:
var numbers = ["92.05, 14.90, 17.90, 14.90"]
然后当你调用numbers.reduce()
时,它只处理字符串中的第一个数字,它不会循环它们。使用包含字符串的变量不会导致它被解析,就像它是Javascript源一样。
你应该这样做:
var numbers = []
for (var i = 0; i < sales.order.length; i++) {
numbers.push(parseFloat(sales.order[i].total_price_usd));
}
或者您可以在此循环中添加,而不是稍后使用reduce()
:
var total = 0;
for (var i = 0; i < sales.order.length; i++) {
total += parseFloat(sales.order[i].total_price_usd);
}
答案 1 :(得分:0)
对变量使用parseFloat()
并将x初始化为0应该有帮助
var sales, i, x = 0;
sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]}
for (i in sales.orders) {
x += parseFloat(sales.orders[i].total_price_usd);
}
var numbers = [x];
function getSum(total, num) {
return parseFloat(total) + parseFloat(num);
}
document.getElementById('sales').innerHTML = '$' + numbers.reduce(getSum);
&#13;
<div id="sales"></div>
&#13;
请注意,在Javascript中添加浮点数会导致一些非常常见的差异。 Is floating point math broken?
答案 2 :(得分:0)
只需使用reduce
和Number
构造函数:
sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]}
const total = sales.orders.reduce(
(total, order) => total + Number(order.total_price_usd),
0
)
console.log(total)
其他人指出,
parseFloat
和一元+
也会奏效。我认为Number是最可读的,但你的里程可能会有所不同。
答案 3 :(得分:0)
sales.orders
getSum
内获取美元num.total_price_usd
var sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]};
//------------- You need to verify this logic
var i, x = ""
// You're creating an array as follow: ["1, 2, 4, 5"].
for (i in sales.orders) {
x += sales.orders[i].total_price_usd + ', ';
}
var numbers = [x];
//-------------------------------------------
function getSum(total, num) {
return parseFloat(total) + parseFloat(num.total_price_usd);
}
document.getElementById('sales').innerHTML = '$' + sales.orders.reduce(getSum, 0);
<p id=sales></p>