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

如何实现JavaScript大小写不敏感搜索?CSV搜索功能故障求助

解决D3.js CSV搜索中Owner字段大小写不敏感的问题

故障原因

崩溃的核心问题是CSV数据里的Culture、Alliance或Owner字段可能存在null、undefined或空值,直接调用.toLowerCase()会触发TypeError(无法对null/undefined调用方法)。另外直接转换inputValue为小写后,若未同步调整对应字段的匹配逻辑,也会导致功能异常。

修复后的代码

// 统一处理输入值:转小写+去除首尾空格,减少重复操作
var inputValue = d3.select("#user-input").property("value").trim().toLowerCase();

var filteredMovies = movies.filter(movie => {
    // Coords字段:按需选择是否大小写不敏感,这里实现包含匹配
    const coordsMatch = movie['Coords'] ? movie['Coords'].toLowerCase().includes(inputValue) : false;
    // City Type字段:先检查字段存在性,再做精确匹配
    const cityTypeMatch = movie['City Type'] ? movie['City Type'].toLowerCase() === inputValue : false;
    // Culture字段:同City Type逻辑
    const cultureMatch = movie['Culture'] ? movie['Culture'].toLowerCase() === inputValue : false;
    // Alliance字段:同City Type逻辑
    const allianceMatch = movie['Alliance'] ? movie['Alliance'].toLowerCase() === inputValue : false;
    // Owner字段:实现大小写不敏感的包含匹配
    const ownerMatch = movie['Owner'] ? movie['Owner'].toLowerCase().includes(inputValue) : false;

    return coordsMatch || cityTypeMatch || cultureMatch || allianceMatch || ownerMatch;
});

关键改动说明

  1. 输入值统一处理:提前将用户输入转小写并去空格,避免在每个字段匹配时重复转换
  2. 字段存在性校验:对每个字段先判断是否存在(movie['字段名'] ? ... : false),防止null/undefined调用方法报错
  3. Owner字段逻辑调整:通过.toLowerCase().includes(inputValue)实现大小写不敏感的包含匹配,和Coords原逻辑一致;若需精确匹配,可替换为===
  4. 语义化变量名:将filter回调参数从movies改为movie,符合遍历单个元素的语义

额外注意事项

  • 若CSV中存在空字符串字段,可将判断条件升级为movie['Owner'] && movie['Owner'].trim() !== '',避免空字符串匹配空输入的情况
  • 若不需要Coords字段的大小写不敏感,可将coordsMatch改回movie['Coords'].includes(inputValue),但仍需保留字段存在性校验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:57:14