如何使用 JavaScript 实现一个简单的购物车系统? - 项越资源网-html css js 用法分享社区-开发交流-项越资源网

如何使用 JavaScript 实现一个简单的购物车系统?

一个简单的购物车系统可以使用以下 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;
}
请登录后发表评论

    没有回复内容