如何遍历对象数组匹配表单值计算披萨订单总价?
披萨订单总价计算问题
我正在开发一个披萨店项目,用户通过表单输入所需披萨尺寸、配料等信息,我需要提取这些值来计算订单总价。目前已完成表单值的提取工作,现请教如何遍历对象数组,匹配此前从表单提取的尺寸和配料值以完成总价计算。
提取表单值的JavaScript代码
let form=document.querySelector("form"); form.addEventListener("submit",(event)=>{ event.preventDefault(); // 提取选中的配料 let topping=[]; document.querySelectorAll('[type="checkbox"]').forEach(item=>{ if (item.checked=== true) { topping.push(item.value); }} ) let pizzaSze=[ {size: "8 inch",cost: 8}, {size: "10 inch", cost:10}, {size: "12 inch", cost:12}, {size:"14 inch", cost:14}, ]; let top=[ {type:"sausage", cost:1}, {type:"pepperoni", cost:1}, {type:"ham", cost:1}, {type:"chicken", cost:1}, {type:"onions", cost:1}, {type:"greenpeppers", cost:1}, ]; // 提取其他表单值 let fullname=document.querySelector("#fullname").value; let address=document.querySelector("#address").value; let pies=document.querySelector("#pies").value; let pizzasize=document.querySelector('input[name="size"]:checked').value;
对应的HTML代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Pizza Assignment</title> </head> <body> <h>Pizza Perfect</h> <br/><br/> <form> <label for="fullname">Please Enter Your First Name:</label> <input type="text" required id="fullname" size="20" name="fullname"> <br/> <br/> <label for="address">Please Enter Your Address:</label> <input type="text" required id="address" size="20" name="address"> <br/> <br/> <label for="pies">Please Enter Number Of Pies:</label> <input type="number" required id="pies" size="20" name="pies"> <br/><br/> <p>Please Enter Size:</p> <input type="radio" id="8 inch" name="size" value="8 inch"> <label for="8 inch">8 inch</label> <br/> <input type="radio" id="10 inch" name="size" value="10 inch"> <label for="10 inch">10 inch</label> <br/> <input type="radio" id="12 inch" name="size" value="12 inch"> <label for="12 inch">12 inch</label> <br/> <input type="radio" id="14 inch" name="size" value="14 inch"> <label for="14 inch">14 inch</label> <br/><br/> <p>Toppings:</p> <input type="checkbox" id="pepperoni" name="topping" value="pepperoni"> <label for="pepperoni">Pepperoni</label> <br/> <input type="checkbox" id="sausage" name="topping" value="sausage"> <label for="sausage">Sausage</label> <br/> <input type="checkbox" id="ham" name="topping" value="ham"> <label for="ham">Ham</label> <br/> <input type="checkbox" id="chicken" name="topping" value="chicken"> <label for="chicken">Chicken</label> <br/> <input type="checkbox" id="onions" name="topping" value="onions"> <label for="onions">Onions</label> <br/> <input type="checkbox" id="greenpeppers" name="topping" value="greenpeppers"> <label for="greenpeppers">Green Peppers</label> <br/><br/> <button type="submit">Submit Order</button> <button type="reset">Reset</button> </form> </body> </html>
解决方案
1. 匹配披萨尺寸成本
使用find()方法快速定位选中尺寸对应的成本:
const sizeCost = pizzaSze.find(item => item.size === pizzasize).cost;
2. 计算配料总成本
通过reduce()遍历选中的配料数组,累加匹配到的配料成本:
const toppingsTotal = topping.reduce((total, selectedTopping) => { const matchingTopping = top.find(item => item.type === selectedTopping); return total + (matchingTopping ? matchingTopping.cost : 0); }, 0);
3. 计算订单总价
将披萨数量转为数字类型,结合尺寸成本和配料总成本计算最终总价:
const numberOfPies = parseInt(pies); const totalOrderCost = (sizeCost + toppingsTotal) * numberOfPies;
整合后的完整代码
将计算逻辑嵌入原有表单提交事件中:
let form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); // 提取选中的配料 let topping = []; document.querySelectorAll('[type="checkbox"]').forEach(item => { if (item.checked === true) { topping.push(item.value); } }); // 价格配置数组 let pizzaSze = [ {size: "8 inch", cost: 8}, {size: "10 inch", cost:10}, {size: "12 inch", cost:12}, {size:"14 inch", cost:14}, ]; let top = [ {type:"sausage", cost:1}, {type:"pepperoni", cost:1}, {type:"ham", cost:1}, {type:"chicken", cost:1}, {type:"onions", cost:1}, {type:"greenpeppers", cost:1}, ]; // 提取其他表单值 let fullname = document.querySelector("#fullname").value; let address = document.querySelector("#address").value; let pies = document.querySelector("#pies").value; let pizzasize = document.querySelector('input[name="size"]:checked').value; // 计算总价 const sizeCost = pizzaSze.find(item => item.size === pizzasize).cost; const toppingsTotal = topping.reduce((total, selected) => { const match = top.find(t => t.type === selected); return total + (match ? match.cost : 0); }, 0); const numberOfPies = parseInt(pies); const totalOrderCost = (sizeCost + toppingsTotal) * numberOfPies; // 输出总价(示例:弹窗显示) alert(`订单总价:$${totalOrderCost}`); console.log(`订单总价:$${totalOrderCost}`); });
优化建议
当选项数量较多时,使用Map结构可以提升查找效率:
// 将价格数组转为Map const sizeCostMap = new Map(pizzaSze.map(item => [item.size, item.cost])); const toppingCostMap = new Map(top.map(item => [item.type, item.cost])); // 快速获取成本 const sizeCost = sizeCostMap.get(pizzasize); const toppingsTotal = topping.reduce((total, selected) => total + (toppingCostMap.get(selected) || 0), 0);
内容的提问来源于stack exchange,提问作者Kelvin Guzman
相关产品推荐
相关产品推荐

