JS 如何实现不使用filter、通过for/forEach返回指定价格区间餐厅列表的函数
修复与实现代码
1. 先修复现有findRestaurantsBySize函数的bug
你的createSizeOfRestaurant返回的对象结构为{size: 尺寸字符串},不存在type属性,且尺寸是单个值不需要嵌套循环判断,修改后代码:
function findRestaurantsBySize(restaurantsBySize, size){ const result = []; for (let i = 0; i < restaurantsBySize.length; i++) { const restaurant = restaurantsBySize[i]; if (restaurant.size.size === size) { result.push(restaurant); } } return result; }
2. 实现findRestaurantsByPriceRange函数
这里提供两种实现,根据你的需求选择:
版本1:精确匹配单个价格等级
如果只需要返回和传入价格等级完全一致的餐厅,直接等值判断即可:
function findRestaurantsByPriceRange(restaurantList, targetPrice) { const result = []; // 用for循环遍历所有餐厅,符合要求则加入结果数组 for (let i = 0; i < restaurantList.length; i++) { const current = restaurantList[i]; if (current.priceRange === targetPrice) { result.push(current); } } return result; } // 测试示例:查找所有中等价位的餐厅 console.log(findRestaurantsByPriceRange(restaurants, 'moderate'))
版本2:支持价格区间查询
如果需要查询某个范围内的餐厅(比如inexpensive到moderate的所有餐厅),可以给价格等级加权重判断:
function findRestaurantsByPriceRange(restaurantList, targetRange) { const result = []; // 定义价格等级权重,值越大档位越高 const priceWeight = { 'inexpensive': 1, 'moderate': 2, 'expensive': 3 }; let minWeight, maxWeight; // 兼容单个档位和区间数组两种传参 if (Array.isArray(targetRange)) { minWeight = priceWeight[targetRange[0]]; maxWeight = priceWeight[targetRange[1]]; } else { minWeight = maxWeight = priceWeight[targetRange]; } for (let i = 0; i < restaurantList.length; i++) { const current = restaurantList[i]; const currentWeight = priceWeight[current.priceRange]; if (currentWeight >= minWeight && currentWeight <= maxWeight) { result.push(current); } } return result; } // 测试示例1:查找所有高档餐厅 console.log(findRestaurantsByPriceRange(restaurants, 'expensive')) // 测试示例2:查找平价到中等价位的所有餐厅 console.log(findRestaurantsByPriceRange(restaurants, ['inexpensive', 'moderate']))
内容的提问来源于stack exchange,提问作者M Alex
相关产品推荐
相关产品推荐

