如何计算数组中的项目数量?

时间:2019-12-09 23:20:58

标签: javascript variables cart

好的,现在您可以在代码中看到,每个项目最多可以添加6个。当您达到6时,它说是极限,然后停止。我们要做的是使代码的产品和价格停在12个项目上。 这是代码。

// Application state.
var state = {
  cart: {
    items: {
      tea: {cost: 2, quantity: 0},
      coffee: {cost: 2.5, quantity: 0},
      avocados: {cost: 3, quantity: 0},
      pizza: {cost: 5, quantity: 0}
    },
    total: 0
  }
};

^这是我在商店中声明不同商品的数组的地方。

// Button methods.
function add(item) {

  const itemToAdd = item.getAttribute("data-item-type");
  if(item.quantity = 12){
    if (state.cart.items[itemToAdd].quantity > 5) {
       $("#" + itemToAdd + "__quantity").text("LIMIT");
         renderCart();
  } else {
    state.cart.items[itemToAdd].quantity += 1;
      $("#" + itemToAdd + "__quantity").text(state.cart.items[itemToAdd].quantity);
        renderCart();
  }
  }else{
      console.log("Top");
  }
}
function subtract(item) {
  const itemToSub = item.getAttribute("data-item-type");
  if (state.cart.items[itemToSub].quantity === 0) {
    return;
  } else {
    state.cart.items[itemToSub].quantity -= 1;
  }
  $("#" + itemToSub + "__quantity").text(state.cart.items[itemToSub].quantity);
  renderCart();
}

// Calculates total for the cart.
function calculateTotal(cart){
  var costs = cart.map(item=>{
    var itemName = item.name;
    var itemPrice = state.cart.items[itemName].cost;
    var quantity = item.quantity;
        return  quantity;
  }).reduce((acc, curr)=>acc+=curr);

  state.cart.total = costs;

  if(costs <= 11){
        $('.total__amount').text(state.cart.total.toFixed(2));
  }else{
        $('.total__amount').text(state.cart.total + " Reached limit");
  }

  var costs = cart.map(item=>{
    var itemName = item.name;
    var itemPrice = state.cart.items[itemName].cost;
    var quantity = item.quantity;
        return  itemPrice * quantity;
  }).reduce((acc, curr)=>acc+=curr);

  state.cart.total = costs;

    if(costs == 12){


        $('.total__number').text(state.cart.total.toFixed(2));
    }else{


        $('.total__number').text(state.cart.total);
    }



}
// Renders cart.
function renderCart() {
  const cart = $(".cart__list");
  cart.empty();
  const cartArray = Object.keys(state.cart.items).map((key, i)=>({
    name: key,
    quantity: state.cart.items[key].quantity
  }))
  cartArray
    .filter(e => e.quantity > 0)
    .map(e => cart.append(`<li class="cart-item">${e.name} &times; ${e.quantity}</li>`));
//   Updates total cost.
  calculateTotal(cartArray);
}

购物车应能够容纳12件物品。每个最多只能选择6个项目。

0 个答案:

没有答案