从购物车中获取总金额的最佳方法是什么?

时间:2018-08-13 19:53:22

标签: javascript json

我目前的购物车存储方式如下:

    let viewUsageIntent = UsageIntent()

    var susbcribers = [INObject]()

    for sub in account.subscribers {
        let inObject = INObject(identifier: sub.phoneNumber, display: sub.id)
        susbcribers.append(inObject)
    }

    viewUsageIntent.suggestedInvocationPhrase = phrase
    viewUsageIntent.ban = account.ban
    viewUsageIntent.subs = susbcribers

    let interaction = INInteraction(intent: viewUsageIntent, response: nil)
    interaction.donate(completion: {
        error in
        if let err = error {
            MyAppServices.Logger.error(tag: "UsageIntentDonation", message: "Donation for ban \(account.ban) could not be completed: \(err.localizedDescription)")
        }
    })

循环浏览购物车并获取金额*价格的总价的最佳方法是什么?我不太清楚...

当前代码:

[ { itemid: '572462', name: 'item1', amount: '1', price: '499' },
  { itemid: '572458', name: 'Item2', amount: '1', price: '699' } ]

这个console.log总是给我一个NaN

4 个答案:

答案 0 :(得分:3)

您的尝试已结束,但由于您的priceamount值是 strings (即用引号引起来)而无法使用。现在,如果您将total变量实例化为0,则代码将意识到您希望将priceamount作为一个数字添加 ,然后按预期工作:

var cart = [ { itemid: '572462', name: 'item1', amount: '1', price: '499' },
  { itemid: '572458', name: 'Item2', amount: '1', price: '699' } ];

var total = 0;
for (let i = 0; i < cart.length; i++) {
  total += cart[i].price * cart[i].amount;
}
console.log(total);


我个人更喜欢使用.reduce()来做这种事情。

var items = [ { itemid: '572462', name: 'item1', amount: '1', price: '499' },
  { itemid: '572458', name: 'Item2', amount: '1', price: '699' } ]
  
var total = items.reduce((total, item) => total + (+item.price * +item.amount), 0);

console.log(total);

.reduce()的工作方式是循环遍历数组中的每个项目并修改“累加器”。累加器是最终将返回的值。例如,如果您试图对数组的项求和,则将执行accummulator + currentItem。最后,您的累加器将是所有数字的总和。

请注意,我为您的item.priceitem.amount加上了一元+运算符,因此字符串值("699")会被转换为整数({ {1}})将它们组合在一起。

答案 1 :(得分:1)

With Array.reduce():

const cartTotal = cart.reduce((total, item) => {
  return total + (Number(item.price) * Number(item.amount));
}, 0);

答案 2 :(得分:1)

  1. 遍历数组
  2. 每次迭代:
    • 获取金额值,转换为整数
    • 获取价格值,转换为整数
    • 将这两个相乘
    • 添加到运行中的总变量

完成后,您的运行总计变量具有总计。

var total;
for (let i = 0; i < cart.length; i++) {
  total += parseInt(cart[i].price) * parseInt(cart[i].amount);
}
console.log(total);

答案 3 :(得分:0)

只需遍历并计算

 var total_price= 0;
var cart_list = [ { itemid: '572462', name: 'item1', amount: '1', price: '499' },
  { itemid: '572458', name: 'Item2', amount: '1', price: '699' } ];

cart_list.forEach(function(obj){
    total_price+= obj.amount*obj.price;
});
console.log(total_price) //this is the total price