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

JavaScript如何实现数组多条件筛选 适配汽车品牌价格类型下拉筛选

汽车多条件筛选功能实现方案

现有代码问题梳理

  • 品牌筛选大小写不匹配:HTML中Seat的option值是小写seat,JSON中存储的品牌名是大写开头Seat,直接比对会匹配失败
  • 价格筛选逻辑错误:原代码直接将下拉选中值和字符串格式的价格比对,没有做数值转换,也没有实现35000阈值的大小判断
  • 车辆类型取值路径错误:标识新旧车的vehicleOwner字段嵌套在detail对象下,原代码直接从车辆根对象取值会获取不到
  • 过滤逻辑位置错误:原代码不管判断结果是否符合,都往结果数组里塞数据,且仅塞单个字段,应该把符合所有条件的完整车辆对象推入结果数组
  • 格式兼容问题:价格是带欧元符号、逗号做小数位的字符串,需要先转成可比较的数值类型

修复后的完整代码

修正后HTML代码

<label for="brands">Brands</label>
<select id="brands" name="carBrands" onchange="getSelectedOptions()">
  <option value="all">All</option>
  <option value="seat">Seat</option>
  <option value="skoda">Škoda</option>
</select>
<label for="prices">Prices</label>
<select id="prices" name="carPrices" onchange="getSelectedOptions()">
  <option value="allPrices">All</option>
  <option value="underPrice">under 35000,00</option>
  <option value="overPrice">over 35000,00</option>
</select>
<label for="types">New and used cars</label>
<select id="types" name="carTypes" onchange="getSelectedOptions()">
  <option value="allTypes">All</option>
  <option value="0">New</option>
  <option value="1">Used</option>
</select>

修正点:补全onchange触发筛选的事件,修正二手车选项的拼写错误,统一类型选项值为字符串格式避免类型不匹配

修正后JS代码

let allCars = [];

// 工具函数:把欧洲格式的价格字符串转成数值
function parsePrice(priceStr) {
  // 去掉欧元符号、空格,把逗号替换成小数点
  return Number(priceStr.replace('€', '').replace(' ', '').replace(',', '.'));
}

function getSelectedOptions() {
  const brand = document.getElementById('brands').value;
  const price = document.getElementById('prices').value;
  const type = document.getElementById('types').value;
  carsFilter(brand, price, type);
}

function carsFilter(brand, price, type) {
  const filteredCars = [];
  const PRICE_THRESHOLD = 35000; // 价格阈值统一维护

  for (let i = 0; i < allCars.length; i++) {
    const currentCar = allCars[i];
    // 品牌条件:全选 或者 统一转小写后匹配,避免大小写问题
    const matchBrand = brand === 'all' || brand === currentCar.brand.toLowerCase();
    // 价格条件:全选 或者 转换后的值符合阈值要求
    const carPrice = parsePrice(currentCar.price);
    let matchPrice = price === 'allPrices';
    if (price === 'underPrice') matchPrice = carPrice < PRICE_THRESHOLD;
    if (price === 'overPrice') matchPrice = carPrice > PRICE_THRESHOLD;
    // 类型条件:全选 或者 和detail下的vehicleOwner匹配
    const matchType = type === 'allTypes' || Number(type) === currentCar.detail.vehicleOwner;

    // 三个条件都符合才加入结果数组
    if (matchBrand && matchPrice && matchType) {
      filteredCars.push(currentCar);
    }
  }
  showCars(filteredCars);
}

核心逻辑说明

  • 价格转换:适配欧洲价格写法,先清理特殊符号再转成可比较的数值,不会出现字符串比对的逻辑错误
  • 条件判断:三个筛选条件为「且」的关系,只有同时满足才会被保留到结果集
  • 兼容性处理:品牌比对统一转小写,类型比对统一转数字,避免大小写、数据类型不一致导致的匹配失败
  • 你之前的showCars函数不需要修改,直接接收完整的车辆对象数组渲染即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:48:03