使用js写一个购买程序
当然!以下是一个简单的JavaScript购买程序示例。这个程序模拟了一个购物车系统,用户可以添加商品到购物车、查看购物车内容以及结账。
// 商品列表
const products = [
{ id: 1, name: '苹果', price: 3 },
{ id: 2, name: '香蕉', price: 2 },
{ id: 3, name: '橙子', price: 4 }
];
// 购物车
let cart = [];
// 添加商品到购物车
function addToCart(productId, quantity) {
const product = products.find(p => p.id === productId);
if (product) {
const cartItem = cart.find(item => item.product.id === productId);
if (cartItem) {
cartItem.quantity += quantity;
} else {
cart.push({ product, quantity });
}
console.log(`${product.name} 已添加到购物车。`);
} else {
console.log('商品未找到。');
}
}
// 查看购物车内容
function viewCart() {
if (cart.length === 0) {
console.log('购物车是空的。');
} else {
console.log('购物车内容:');
cart.forEach(item => {
console.log(`${item.product.name} - 数量: ${item.quantity} - 单价: ${item.product.price} - 总价: ${item.product.price * item.quantity}`);
});
}
}
// 结账
function checkout() {
if (cart.length === 0) {
console.log('购物车是空的,无法结账。');
} else {
let total = 0;
cart.forEach(item => {
total += item.product.price * item.quantity;
});
console.log(`总金额: ${total} 元`);
cart = []; // 清空购物车
console.log('结账成功,购物车已清空。');
}
}
// 示例操作
addToCart(1, 2); // 添加2个苹果到购物车
addToCart(2, 3); // 添加3个香蕉到购物车
viewCart(); // 查看购物车内容
checkout(); // 结账
viewCart(); // 查看购物车内容
这个程序包括以下功能:
addToCart(productId, quantity)
:将指定数量的商品添加到购物车。viewCart()
:查看购物车的内容。checkout()
:结账并清空购物车。你可以根据需要扩展这个程序,例如添加更多的商品、处理库存、用户登录等