一个简单的购物车系统可以使用以下 JavaScript 代码实现:
// Initialize empty cart
let cart = [];
// Add items to the cart
function addToCart(item,quantity) {
cart.push({
item: item,
quantity: quantity
});
console.log('The item "' + item + '" has been added to your cart.');
}
// Remove a single item from the cart
function removeFromCart(item) {
for (let i = 0; i < cart.length; i++) {
if (cart[i].item === item) {
cart.splice(i,1);
console.log('Item "' + item + '" was successfully removed!');
}
}
}
// Calculate the total cost of the item in the cart
function calculateTotalPrice() {
let total = 0;
for (let i = 0; i < cart.length; i++) {
total += (cart[i].price * cart[i].quantity);
}
return total;
}
没有回复内容