我在下面的代码创建了在JavaScript项目。 什么已经给我的问题是如何建立一个购物车(数组字典)这是要对自己的一个函数,将保留项目名称和价格从下面的代码。 这是我所应该做的:添加物品到购物车,并计算在车中所有总所有项目,删除项目,并执行(以车总降价),并从车秀项对应的计算。
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();
OUTPUT
[
{"name":"BAG","price":50,"quantity":80,"total":0},
{"name":"BEAD","price":1,"quantity":120,"total":0},
{"name":"CANDLE","price":20,"quantity":5,"total":0}
]
文章来源: How can i create a cart(dictionary function) to add and remove items in javascript