如何将对象内的order函数传入orderDelivery函数实现订单同步?
解决订单同步问题:整合order与orderDelivery函数
核心目标是让orderDelivery复用order的逻辑,避免硬编码索引,同时保证订单数据同步。以下是两种可行实现方式:
方案一:内部调用order生成订单(推荐)
修改orderDelivery函数,内部调用order获取菜品,不再直接访问starterMenu和mainMenu,确保逻辑统一:
const restaurant = { name: 'Classico Italiano', location: 'Via Angelo Tavanti 23, Firenze, Italy', categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'], starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'], mainMenu: ['Pizza', 'Pasta', 'Risotto'], openingHours: { thu: { open: 12, close: 22 }, fri: { open: 11, close: 23 }, sat: { open: 0, close: 24 }, }, order: function (starterIndex, mainIndex) { return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; }, orderDelivery: function({ starterIndex, mainIndex, time, address }) { // 调用order函数获取菜品,解构赋值 const [starterDish, mainDish] = this.order(starterIndex, mainIndex); console.log(`Order received! ${starterDish} and ${mainDish} will be delivered to ${address} at ${time}`); } }; // 调用时传入索引,内部自动生成订单 restaurant.orderDelivery({ time: '22:30', address: 'Via del Sole, 21', starterIndex: 2, mainIndex: 1 });
方案二:支持传入索引或直接传入菜品(灵活扩展)
如果需要同时支持“传索引生成订单”和“直接传已生成的菜品”,可以修改orderDelivery增加兼容逻辑:
const restaurant = { // 其他属性不变... orderDelivery: function({ starter, main, starterIndex, mainIndex, time, address }) { // 优先使用传入的菜品,无菜品时调用order生成 const finalStarter = starter || this.order(starterIndex, mainIndex)[0]; const finalMain = main || this.order(starterIndex, mainIndex)[1]; console.log(`Order received! ${finalStarter} and ${finalMain} will be delivered to ${address} at ${time}`); } }; // 方式1:传索引生成订单 restaurant.orderDelivery({ time: '22:30', address: 'Via del Sole, 21', starterIndex: 2, mainIndex: 1 }); // 方式2:直接传入已生成的订单 const preOrdered = restaurant.order(2, 1); restaurant.orderDelivery({ time: '22:30', address: 'Via del Sole, 21', starter: preOrdered[0], main: preOrdered[1] });
你之前尝试失败的原因
- 尝试1的解构错误:直接写
({starterIndex, mainIndex}) = this.order(2,1)不符合语法,且硬编码了索引值,无法动态接收外部参数。正确的解构需要声明变量(如const [s, m] = this.order(...))。 - 尝试2未赋值:仅调用
this.order(2,1)但未将返回值赋值给变量,console.log仍使用未传入的starterIndex和mainIndex,导致输出undefined。 - 尝试3参数类型错误:将
myOrder[0](菜品名称字符串)传给mainIndex,而mainIndex需要数字索引,导致this.mainMenu[字符串]无法找到对应菜品,返回undefined。
内容的提问来源于stack exchange,提问作者Savior-code
相关产品推荐
相关产品推荐

