如何访问对象构造函数中的数组参数并计算客户订单总价
解决客户订单数组undefined问题并实现总价计算功能
我来帮你搞定这个问题!你遇到的undefined问题主要是拼写混乱和逻辑疏漏导致的,同时我会帮你实现订单总价自动累加的功能,让Timo订购Keyboard和mouse后能正确算出总价格。
先梳理你代码里的核心问题
- 拼写错误满天飞:
Costumer/Customer、costumer/costumers/custumer这些拼写混乱,导致变量引用错误,这是undefined的主要原因。 - 构造函数逻辑缺失:
Costumer构造函数里没有正确接收order参数,total也没有初始化逻辑,导致订单数组和总价无法正常工作。 - 表单提交逻辑错误:未定义的
itemItem、错误引用waiter.order(你根本没定义waiter对象),还有没有正确关联选中的商品和客户。 - 初始数组访问错误:你用
console.log(costomer[0].order[1])时,不仅拼写错了数组名(应该是costumers),而且初始时客户的order是空数组,访问索引1自然返回undefined。
修正后的完整代码
// 统一拼写为Customer(符合英文规范) function Customer(name, order = [], total = 0) { this.name = name; this.order = order; // 正确接收传入的order参数,默认空数组 this.total = total; // 初始化总价为0 } // 客户数组(拼写正确为customers) const customers = [ new Customer('Timo'), new Customer('Bill') ]; // 获取客户选择框元素(假设你HTML里的id是customerEl) const customerEl = document.getElementById('customerEl'); // 填充客户选择框:用正确的customers数组遍历 customers.forEach(({ name }) => customerEl.options.add(new Option(name))); // Item构造函数保持不变 function Item(item, price) { this.item = item; this.price = price; } // 商品数组 const items = [ new Item('Keyboard', 14.50), new Item('mouse', 10) ]; // 获取商品选择框元素(假设你HTML里的id是foodMain) const foodMain = document.getElementById('foodMain'); // 填充商品选择框(之前你没做这一步,得加上) items.forEach(({ item }) => foodMain.options.add(new Option(item))); // 获取表单元素 const formEl = document.getElementById('mainForm'); formEl.onsubmit = function(e) { e.preventDefault(); // 用标准的preventDefault阻止刷新,替代return false // 获取选中的商品名称和客户名称 const selectedItemName = foodMain.options[foodMain.selectedIndex].value; const selectedCustomerName = customerEl.options[customerEl.selectedIndex].value; // 找到对应的客户和商品对象 const targetCustomer = customers.find(customer => customer.name === selectedCustomerName); const targetItem = items.find(item => item.item === selectedItemName); // 确保找到客户和商品后再执行逻辑 if (targetCustomer && targetItem) { // 把商品添加到客户的订单数组 targetCustomer.order.push(targetItem); // 累加总价:把当前商品价格加到客户的total属性上 targetCustomer.total += targetItem.price; // 测试输出:查看客户的订单和总价 console.log(`${selectedCustomerName}的订单:`, targetCustomer.order); console.log(`${selectedCustomerName}的订单总价:`, targetCustomer.total); } };
关键修改点说明
- 统一拼写规范:把所有客户相关的拼写统一为
Customer(构造函数)、customers(数组)、customerEl(DOM元素),彻底解决拼写错误导致的undefined。 - 完善构造函数:给
Customer构造函数添加默认参数,初始化order为空数组、total为0,同时正确接收传入的订单数据。 - 补全商品选择框填充:之前你只填充了客户选择框,商品选择框也需要遍历
items数组填充,否则无法选择商品。 - 修复表单提交逻辑:
- 用
e.preventDefault()替代return false,更符合现代JS规范。 - 正确找到选中的客户和商品对象,避免未定义变量。
- 把商品添加到对应客户的
order数组,同时自动累加total总价。
- 用
- 解决初始访问undefined:现在如果要查看Timo的订单,应该用
console.log(customers[0].order),初始是空数组,添加商品后就能看到对应的Item对象,访问索引也不会再返回undefined。
现在你测试一下:选择Timo,先选Keyboard提交,再选mouse提交,控制台会输出Timo的订单总价为24.50,完全符合你的需求!
内容的提问来源于stack exchange,提问作者Liam
相关产品推荐
相关产品推荐

