javascript購物車代碼是什么 購物車jquery代碼
Pontofrio優(yōu)選生活跨境問答2025-05-255980
// 購物車類
class ShoppingCart {
constructor() {
this.items = [];
}
// 添加商品到購物車
addItem(item) {
this.items.push(item);
}
// 從購物車中移除商品
removeItem(item) {
const index = this.items.indexOf(item);
if (index > -1) {
this.items.splice(index, 1);
}
}
// 計算購物車總價
getTotalPrice() {
return this.items.reduce((total, item) => total + item.price, 0);
}
}
// 示例:創(chuàng)建一個購物車并添加商品
const cart = new ShoppingCart();
cart.addItem({ name: '商品1', price: 100 });
cart.addItem({ name: '商品2', price: 200 });
// 輸出購物車總價
console.log(cart.getTotalPrice()); // 輸出:300
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。