import java.util.ArrayList;import java.util.Listfor (Item item : items) {totalQuantity += item.getQuantity();}return totalQuantity;}public List- getItems() {return this.items;}}public class Item {private String name;private double price;private int quantity;public Item(String name, double price, int quantity) {this.name = name;this.price = price;this.quantity = quantity;}public String getName() {return this.name;}public double getPrice() {return this.price;}public int getQuantity() {return this.quantity;}public void setQuantity(int quantity) {this.quantity = quantity;}}
const shoppingCart = {items: [],addItem: function(item) {this.items.push(item);},getTotalPrice: function() {let totalPrice = 0;for (let item of this.items) {totalPrice += item.price item.quantity;}return totalPrice;},getTotalQuantity: function() {let totalQuantity = 0;for (let item of this.items) {totalQuantity += item.quantity;}return totalQuantity;},getItems: function() {return this.items;}};const item1 = {name: '苹果',price: 2.5,quantity: 3};const item2 = {name: '香蕉',price: 1.8,quantity: 5};shoppingCart.addItem(item1);shoppingCart.addItem(item2);console.log(`购物车中商品总数:${shoppingCart.getTotalQuantity()}`);console.log(`购物车中商品总价:${shoppingCart.getTotalPrice()}`);console.log(shoppingCart.getItems());
本文地址:https://www.qianwe.cn/article/5095bd6f98aa22264511.html