我在javascript中创建了以下代码。给我提出问题的是如何创建一个CART(数组字典),它本身就是一个函数,它将保存下面代码中的项目名称和价格。这是我应该做的事情:将物品添加到购物车并计算购物车中所有物品的总数,移除物品并进行相应的计算(降低购物车总价)并显示购物车中的物品。
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();
答案 0 :(得分:0)
我有一点时间,所以我想我会解决这个问题。
由于<numeric>
的实例是对象,因此最好将它们存储在数组中。数组有许多有用的方法可以操作数据以满足您的需求。
让我们创建购物车。
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
You can the other code changes here
制作新购物车。
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();