我真的是 javascript 的新手,所以請原諒我在提出問題時出現的任何錯誤。我有以下物件,并試圖弄清楚如何找到所有專案的總數量。我正在尋找“17”的輸出。
這是物件:
const cart = {
"tax": .10,
"items": [
{
"title": "milk",
"price": 4.99,
"quantity": 2
},
{
"title": "rice",
"price": 0.99,
"quantity": 2
},
{
"title": "candy",
"price": 0.99,
"quantity": 3
},
{
"title": "bread",
"price": 2.99,
"quantity": 1
},
{
"title": "apples",
"price": 0.75,
"quantity": 9
}
]
}
在過去的 4 個小時里,我一直在努力尋找解決方案。這包括嘗試查找有關如何理解嵌套在屬性中的物件/陣列的視頻/書面資訊。任何幫助指向正確方向的幫助將不勝感激。謝謝你。
uj5u.com熱心網友回復:
遍歷“items”陣列并添加所有數量:
let sum = 0;
for(let i = 0; i < cart.items.length; i ){
sum = cart.items[i].quantity;
}
console.log(sum) // Should be 17.
uj5u.com熱心網友回復:
您必須將以下代碼與最佳實踐一起使用。
const cart = {
"tax": .10,
"items": [
{
"title": "milk",
"price": 4.99,
"quantity": 2
},
{
"title": "rice",
"price": 0.99,
"quantity": 2
},
{
"title": "candy",
"price": 0.99,
"quantity": 3
},
{
"title": "bread",
"price": 2.99,
"quantity": 1
},
{
"title": "apples",
"price": 0.75,
"quantity": 9
}
]};
let items = cart.items;
let sum = 0;
items.forEach(function(item){
sum = item.quantity
});
console.log(sum)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535338.html
上一篇:索引/匹配/大型多重標準
