You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何改造单参数筛选函数实现多条件AND匹配及对象参数兼容

解决方案

问题1:传category1变量无法返回正确结果的修复

原因

你定义的category1是createCategory函数生成的对象,实际结构为{ type: 'Chinese' },但所有餐厅实例的category属性中存储的是字符串类型的分类名,用includes匹配对象和字符串永远返回false,因此无法命中结果。

修复方案二选一:

  • 传参时取分类对象的type属性:
    console.log(findRestaurantsByCategory(restaurants, category1.type));
    
  • 统一数据结构:修改餐厅创建逻辑,category字段存储分类对象而非字符串,例:
    let restaurant1 = createRestaurant('Rosetto', 'Boulevar 2', 500, 71, [category1, category2, category3, category4], 8, 20);
    

问题2:支持多分类同时匹配的函数改造

改造后的函数兼容单个分类/分类数组输入,仅返回同时满足所有筛选分类的餐厅:

function findRestaurantsByCategory(restaurantsByCategory, categories){
  // 统一把筛选参数转为数组格式,兼容单值输入
  const filterList = Array.isArray(categories) ? categories : [categories];
  // 统一把筛选条件转为字符串,兼容传分类对象的场景
  const filterStrList = filterList.map(item => typeof item === 'string' ? item : item.type);

  const result = [];
  for (let i = 0; i < restaurantsByCategory.length; i++) {
    const currentCates = restaurantsByCategory[i].category;
    // 检查当前餐厅是否包含所有筛选分类
    const isMatch = filterStrList.every(cate => currentCates.includes(cate));
    if (isMatch) {
      result.push(restaurantsByCategory[i]);
    }
  }
  return result;
}

调用示例

// 传分类数组,返回同时包含International和Balkan的餐厅:restaurant1、restaurant3
console.log(findRestaurantsByCategory(restaurants, ['International', 'Balkan']));
// 传单个分类对象也可正常生效
console.log(findRestaurantsByCategory(restaurants, category1));

内容的提问来源于stack exchange,提问作者M Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:57:03