如何在引用嵌套函数内部参数的函数内部使用条件语句以在javascript中返回结果?

我有一个购物车,需要在该购物车中添加一个有条件的折扣,该函数当前可以获取商品的价格并将其乘以数量。当前,该功能就像没有折扣的护身符一样工作,但是折扣需要能够判断是否有两个或多个带有相同“标签”的商品(例如“奶酪比萨”,“蘑菇比萨”,“夏威夷比萨”)然后从返回的总数中减去一定金额即可使用。我该如何实现?

此功能获取用户购物车中所有商品的总价

 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;
}

此函数在上述函数内部。它用于获取单个项目的小计,包括其选项

getItemTotal(item) {
 let total = item.price * item.quantity;

  item.options.forEach(option => (total += option.value * item.quantity));
  return total;
  }

以下是带有奶酪“标签”的商品的示例。条件块需要确定是否有两个标签与奶酪相似,然后在第一个功能中从总计中减去$ 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"],
     }
     ]
评论
  • 转身说再见
    转身说再见 回复

    You can access the item inside the forEach loop callback.

    您可以使用计数器来计算带有特定标签的项目数。这是一个例子:

    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;
    }