為了實(shí)現(xiàn)一個(gè)購物車計(jì)算價(jià)格的功能,我們需要先定義商品的價(jià)格。然后,根據(jù)購物車內(nèi)商品的總價(jià)進(jìn)行計(jì)算。
我們需要?jiǎng)?chuàng)建一個(gè)商品類,包含商品名稱、價(jià)格和數(shù)量等屬性:
class Item {
constructor(name, price, quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
接下來,我們創(chuàng)建一個(gè)購物車類,包含商品列表和總價(jià)等屬性:
class ShoppingCart {
constructor() {
this.items = [];
}
// 添加商品到購物車
addItem(item) {
this.items.push(item);
}
// 計(jì)算購物車總價(jià)
calculateTotalPrice() {
return this.items.reduce((total, item) => total + (item.price * item.quantity), 0);
}
}
我們可以使用這兩個(gè)類來實(shí)現(xiàn)購物車計(jì)算價(jià)格的功能:
// 創(chuàng)建商品列表
const items = [
new Item("商品1", 100, 2),
new Item("商品2", 200, 3),
new Item("商品3", 300, 1),
];
// 創(chuàng)建購物車實(shí)例
const cart = new ShoppingCart();
// 添加商品到購物車
cart.addItem(items[0]);
cart.addItem(items[1]);
cart.addItem(items[2]);
// 計(jì)算購物車總價(jià)
console.log("購物車總價(jià):" + cart.calculateTotalPrice());
運(yùn)行上述代碼,將輸出購物車總價(jià)為:購物車總價(jià):600
。
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。