【发布时间】:2022-01-01 18:10:12
【问题描述】:
var groceries = [
{
id: 1,
product: 'Olive Oil',
price: '$' + 12.1
},
{
id: 2,
product: 'Tomato Soup',
price: '$' + 3.48
},
{
id: 3,
product: 'Cheesecake',
price: '$' + 17.36
},
{
id: 4,
product: 'Sirloin Steak',
price: '$' + 14.8
},
{
id: 5,
product: 'Brie Cheese',
price: '$' + 23.28
}
];
var sum = _.reduce(products, function (total, price) {
return total + price;
}, 0);
在我们开始添加价值之前,我不太确定如何从价格中删除“$”。我已经尽力在这里寻找其他解决方案(我是新手),但似乎只有“价格”只是数字的例子。
对不起,如果这个类似的问题已经在其他地方发布了,但我仍在学习如何在这里导航,除非有人能指出我,否则我还没有找到类似的情况!
【问题讨论】:
-
一种方法是
return total + parseFloat(price.slice(1));,但正如后来的 cmets 建议的那样,存储货币并不是最好的举措。只需存储数字,稍后添加货币即可显示。 -
您可以控制
groceries数据吗?如果是这样,您能否向仅包含原始价格数字值的对象添加另一个属性(例如priceNumber: 21.1) -
为什么不存储没有货币符号的价格。如有必要,将其存储在不同的属性中。
-
@NickParsons 不幸的是,我无法控制数据..
标签: javascript string integer reduce