使用JavaScript筛选数组:根据用户输入筛选酒店星级
解决酒店星级筛选问题
嘿,我来帮你搞定这个酒店筛选的需求!其实实现起来很简单,核心就是用数组的filter()方法来过滤符合条件的酒店,不过有个小细节要注意——你代码里的stars属性是字符串类型(比如"5"),直接和数字比较会出问题,得先转成数字再判断。
完整实现步骤
先给你补全代码并加上筛选功能,一步步看:
class Hotel { constructor(name, stars, distance, wifi, pool, price){ this.name = name; // 建议在这里就把stars转成数字,后续处理更方便 this.stars = Number(stars); this.distance = distance; this.wifi = wifi; this.pool = pool; this.price = price; } } var hotels=[]; hotels.push(new Hotel("The Grand", "5","0.5","yes","no","190")); hotels.push(new Hotel("The Plaza", "3","1.2","yes","yes","120")); hotels.push(new Hotel("Budget Inn", "2","2.0","no","no","60")); hotels.push(new Hotel("Luxury Resort", "4","0.8","yes","yes","150")); // 定义筛选函数:传入星级阈值,返回符合条件的酒店数组 function filterHotelsByMinStars(minStar) { // 先确保阈值是数字类型 const threshold = Number(minStar); if (isNaN(threshold)) { console.log("请输入有效的数字哦!"); return []; } // 使用filter过滤,判断酒店星级是否≥阈值 return hotels.filter(hotel => hotel.stars >= threshold); } // 调用示例:用户输入3,筛选3星及以上的酒店 const userInput = 3; const filteredHotels = filterHotelsByMinStars(userInput); console.log("筛选结果:", filteredHotels);
关键细节说明
- 转数字处理:我在
Hotel的构造函数里就把stars转成了数字,这样后续筛选不用每次都转;如果不想修改构造函数,也可以在filter回调里转:Number(hotel.stars) >= threshold。 - filter方法:
filter()会遍历数组,对每个元素执行回调函数,返回true的元素会被保留到新数组里,完美符合筛选需求。 - 健壮性处理:加了
isNaN判断,如果用户输入的不是有效数字,会提示并返回空数组,避免出错。
运行效果
当你输入3时,会得到以下结果:
[Hotel { name: 'The Grand', stars: 5, ... }, Hotel { name: 'The Plaza', stars: 3, ... }, Hotel { name: 'Luxury Resort', stars: 4, ... }]
这样就实现了你想要的功能啦!如果还有其他筛选需求(比如按价格、是否有泳池),用类似的filter方法就能轻松扩展~
内容的提问来源于stack exchange,提问作者user9575743
相关产品推荐
相关产品推荐

