[英]How can use a conditional statement inside of a function that references the parameter inside of a nested function to return a result in javascript?
我有一個購物車,我需要能夠向 function 添加有條件的折扣,該 function 當前獲取商品的價格並將其乘以數量。 目前,function 就像沒有折扣的魅力,但折扣需要能夠判斷是否有兩個或多個具有相同“標簽”的商品(例如“奶酪披薩”、“蘑菇披薩”、“夏威夷披薩”)然后從返回的總數中減去一個金額以使其工作。 我如何實現這一目標?
這個 function 獲取用戶購物車中所有商品項目的總價格金額
get totalAmount() {
let total = 0;
this.cart.forEach(item => (total += this.getItemTotal(item)));
///// possible conditional statement here
////// something like if (item.tags == "cheese"){
/////// return total - 2; }
//////// ( currently just errors out to "**item not found**" even though I thought
///// since the parameter "item" was in the function within the function it could recognize it)
return total;
}
這個 function 在上面的 function 里面。 它用於獲取單個項目的小計,包括它的選項
getItemTotal(item) {
let total = item.price * item.quantity;
item.options.forEach(option => (total += option.value * item.quantity));
return total;
}
下面是一個帶有奶酪“標簽”的項目示例。 條件塊需要判斷是否有兩個標簽與奶酪相似,然后從第一個 function 中的總和中取出 2 美元
"item": [
{
"id": 1,
"guid": "1d4aa3b2-c059-4fa7-a751-9bca735e4ea1",
"thumb": "https://foodorderingapp9309.s3-us-west-
1.amazonaws.com/CheesySenstions/menu/CheesePizza.JPG",
"title": "Cheese",
"body": "try new cheese pizza",
"tags": ["pizza"],
}
]
您可以訪問forEach
循環回調中的項目。
您可以使用計數器來計算具有特定標簽的項目數。 這是一個例子:
get totalAmount() {
let total = 0;
let numberOfItemsWithCheeseTag = 0;
this.cart.forEach(item => {
total += this.getItemTotal(item);
// Increment the counter if 'cheese' is one of the tags
if (item.tags.includes('cheese')) {
numberOfItemsWithCheeseTag += 1; //
}
});
// Apply the discount if the counter reached a threshold
if (numberOfItemsWithCheeseTag >= 2) {
total -= 2;
}
return total;
}
這是一個不同的看法
get totalAmount() {
let total = this.cart.reduce((t, item) => t + this.getItemTotal(item), 0)
const count = this.cart.reduce((c, item) => c + item.tags.includes('cheese'), 0)
if (count >= 2) {
return total -= 2
}
return total
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.