【问题标题】: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?如何在引用嵌套函数内部参数的函数内部使用条件语句以在 javascript 中返回结果?
【发布时间】:2020-07-21 10:46:01
【问题描述】:

我有一个购物车,我需要在其中向当前获取商品价格并将其乘以数量的函数添加条件折扣。目前,该功能就像没有折扣的魅力,但是折扣需要能够判断是否有两个或多个具有相同“标签”的商品(例如“奶酪披萨”、“蘑菇披萨”、“夏威夷披萨”)然后从返回的总数中减去一个金额以使其工作。我如何做到这一点?

此函数获取用户购物车中所有商品的总价格金额

 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"],
     }
     ]

【问题讨论】:

    标签: javascript arrays foreach parameters arrow-functions


    【解决方案1】:

    您可以在forEach 循环回调中访问该项目。

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

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

    【讨论】:

      【解决方案2】:

      这里有不同的看法

      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
      }
      

      【讨论】:

        猜你喜欢
        • 2016-10-06
        • 2014-05-27
        • 2019-09-02
        • 1970-01-01
        • 2023-02-23
        • 2022-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多