如何创建一个购物车(字典函数)以在JavaScript中添加和删除项目



我在JavaScript中为Item创建了以下代码。一直给我的问题是如何创建一个购物车(数组词典),该函数本身将从下面的代码中保留项目名称和价格。这是我期望要做的:将项目添加到购物车并计算购物车中所有项目的所有总数,删除项目并进行相应的计算(降低了购物车的总价),并显示了购物车中的项目。

function item(name) {
  this.price = 0;
  this.quantity = 0;
  this.total = 0;
};
item.prototype = {
  setItemPrice: function (itemPrice) {
    this.price = itemPrice;
  },
  setQuantity: function (itemUnit) {
    this.quantity = itemUnit;
  },
  itemTotal: function () {
    return this.total += this.price * this.quantity;
  }
}
bag = new item('BAG');
bag.setItemPrice(50);
bag.setQuantity(80);
bag.setQuantity(90);
bag.itemTotal();

我有一点时间,所以我想我要解决这个问题。

由于item的实例是对象,因此最好将它们存储在数组中。阵列有许多有用的方法可以操纵数据以符合您的需求。

让我们创建购物车。

// Cart is capitalised.
// It is a JS best-practice to capitalise your constructor function
// names to differentiate them from other functions
function Cart() {
  // We only need an array here
  this.items = [];
  // But this is new.
  // Returning the object allows you to chain instance methods
  // together when the object has been instantiated
  return this;
}
Cart.prototype = {
  addItem: function (item) {
    // Push a new item object into the cart array
    this.items.push(item);
    return this;
  },
  removeItem: function (name) {
    // We pass in the name of an item
    // and use filter` to filter/return all of the items *without*
    // that name (thus removing the item we don't want)
    this.items = this.items.filter(function (item) {
      return item.name !== name;
    });
  },
  showCart: function () {
    // `showCart` simply returns the array
    return this.items;
  },
  getCartTotal: function () {
    // `reduce` is another useful function and allows us
    // to use a function to return each item total
    // and add it to the accumulated total
    return this.items.reduce(function (total, item) {
      return total + (item.quantity * item.price);
    }, 0);
  }
}

我也对Item构造函数进行了修改,基本上是在return this中添加到方法中,因此您可以执行此操作:

const bag = new Item('BAG').setItemPrice(50).setQuantity(80);
const scarf = new Item('SCARF').setItemPrice(10).setQuantity(20);
const bead = new Item('BEAD').setItemPrice(1).setQuantity(120);
const candle = new Item('CANDLE').setItemPrice(20).setQuantity(5);

您可以在此处更改其他代码。

创建新的购物车。

const cart = new Cart();

现在我们可以添加项目

cart.addItem(bag).addItem(scarf).addItem(bead).addItem(candle);

获取总数:

cart.getCartTotal(); // 4420

删除围巾项目:

cart.removeItem('SCARF');

获取新的购物车:

cart.getCartTotal(); // 4220

显示购物车:

cart.showCart();

输出

[
  {"name":"BAG","price":50,"quantity":80,"total":0},
  {"name":"BEAD","price":1,"quantity":120,"total":0},
  {"name":"CANDLE","price":20,"quantity":5,"total":0}
]

最新更新