如何根据传入城市参数过滤餐厅名称?解决代码输出undefined问题
问题分析与解决方法
代码中的核心问题
- 未传入过滤参数:调用
filterRestaurantByCity()时没有传递目标城市,导致函数内的过滤条件失效,得到空数组。 - 错误访问数组属性:
filter()方法返回的是匹配元素组成的数组,直接访问b.name会因为数组没有name属性而输出undefined。 - 参数命名不规范:用具体城市名
Varanasi作为参数名,不符合通用函数的设计逻辑,应该使用通用名称。
修正后的代码
class restaurantManager { constructor() { this.restaurantList = [{ name: "Barbeque Nation", address: "Phulwariya", city: "Varanasi" }, { name: "The Table", address: "Cantt Station", city: "Bengluru" }, { name: "i love my wife", address: "Lohamandi", city: "Pune" }, { name: "Batti chokha", address: "Maldhiya", city: "Delhi" } ] } filterRestaurantByCity(targetCity) { // 过滤出匹配目标城市的餐厅数组 let matchedRestaurants = this.restaurantList.filter(item => item.city === targetCity); // 提取所有匹配餐厅的名称 let restaurantNames = matchedRestaurants.map(restaurant => restaurant.name); console.log(restaurantNames); // 可选:返回结果供后续使用 return restaurantNames; } } let myobject = new restaurantManager() // 调用时传入目标城市参数 let c = myobject.filterRestaurantByCity("Varanasi")
关键修改说明
- 传递过滤参数:调用函数时传入具体城市(如
"Varanasi"),确保过滤条件生效。 - 正确处理过滤结果:先用
filter()获取匹配的餐厅数组,再通过map()提取每个餐厅的name属性,输出餐厅名称数组。 - 规范参数命名:将参数名改为
targetCity,让函数可适配任意城市的查询需求。
内容的提问来源于stack exchange,提问作者Ujala
相关产品推荐
相关产品推荐

