【问题标题】:How to find the total of values in array如何查找数组中的值的总和
【发布时间】:2022-08-02 20:08:18
【问题描述】:

我正在制作一个电子商务网站,但我不知道如何找到确切的价格总和

我不知道如何得到价格的总和

我尝试了其他方法,例如 reduce 但不起作用

代码 :

const cartItems =  [
        {
        \"category\": \"featured\",
        \"condition\": \"New\",
        \"name\": \"Women jacket\",
        \"price\": \"650\",
        \"quantity\": \"5\",
        \"size\": \"md\"
        },
        {
        \"category\": \"featured\",
        \"condition\": \"New\",
        \"name\": \"Nike shoes\",
        \"price\": \"3000\",
        \"quantity\": \"6\",
        \"size\": \"md\"
        },
        {
        \"category\": \"featured\",
        \"condition\": \"New\",
        \"name\": \"Mens Crusher Tee\",
        \"price\": \"2000\",
        \"quantity\": \"7\",
        \"size\": \"xl\"
        },
        {
        \"category\": \"featured\",
        \"condition\": \"New\",
        \"name\": \"Creatsy tote bag\",
        \"price\": \"1200\",
        \"quantity\": \"8\",
        \"size\": \"Big\"
    }
]
  • 您能否包含不起作用的代码(例如您的 reduce 尝试)?
  • 您能否向我们展示您尝试使用的 reduce 功能以及为什么它不起作用?
  • \"我尝试了其他方法,例如 reduce\"请包括您的尝试,以便我们帮助您了解问题所在。不要在不付出任何努力的情况下期待答案。 -> Minimal, Reproducible Example

标签: javascript html reactjs


【解决方案1】:

您可以使用reduce

const cartItems =  [
        {
        "category": "featured",
        "condition": "New",
        "name": "Women jacket",
        "price": "650",
        "quantity": "5",
        "size": "md"
        },
        {
        "category": "featured",
        "condition": "New",
        "name": "Nike shoes",
        "price": "3000",
        "quantity": "6",
        "size": "md"
        },
        {
        "category": "featured",
        "condition": "New",
        "name": "Mens Crusher Tee",
        "price": "2000",
        "quantity": "7",
        "size": "xl"
        },
        {
        "category": "featured",
        "condition": "New",
        "name": "Creatsy tote bag",
        "price": "1200",
        "quantity": "8",
        "size": "Big"
    }
]

function sumPrices(items) {
  return items.reduce((acc, value) => parseFloat(value.price) + acc, 0)
}

console.log(sumPrices(cartItems))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2013-09-13
    • 1970-01-01
    • 2020-04-06
    • 2017-06-04
    • 2013-10-11
    • 1970-01-01
    相关资源
    最近更新 更多