JavaScript布尔表达式执行异常:搜索仅state匹配成功,lga等字段无结果
问题排查与修复方案
核心错误原因
- 索引复用逻辑错误:外层循环的变量
i是theProjects数组的遍历索引,直接用同一个i访问子数组lga[i]、communities[i]的逻辑完全不成立。子数组的长度和外层theProjects数组长度没有关联,绝大多数场景下会读取到undefined值,自然无法匹配到lga名和社区名。 - 缺少子数组遍历逻辑:
lga和communities都是数组类型,需要嵌套循环遍历每个项目下的所有lga条目、每个lga下的所有社区条目,才能完成全量字段匹配。 - 匹配结果覆盖风险:当前逻辑如果命中多个匹配项,后匹配的内容会直接覆盖之前的
dataObject,最终只会返回最后一个匹配的结果,建议用数组存储全量匹配结果。
修复后代码
function getSearch(req, res, next) { let theProjects = shared.projects; // 用数组存储所有匹配结果,避免覆盖 let matchResults = []; const search = req.body.searchWork; // 遍历所有项目 for (let i = 0; i < theProjects.length; i++) { const currentProject = theProjects[i]; // 先匹配state字段 let stateMatch = search === currentProject.state; // 遍历当前项目下的所有lga for (let j = 0; j < currentProject.lga.length; j++) { const currentLga = currentProject.lga[j]; let lgaMatch = search === currentLga.lgaName; // 遍历当前lga下的所有社区 for (let k = 0; k < currentLga.communities.length; k++) { const currentCommunity = currentLga.communities[k]; let communityMatch = search === currentCommunity.nameOfCommunity; // 任意字段匹配就存入结果 if (stateMatch || lgaMatch || communityMatch) { matchResults.push({ state: currentProject.state, lga: currentLga.lgaName, community: currentCommunity.nameOfCommunity, project: currentCommunity.projects.building }); } } } } console.log(matchResults); // 若仅需返回单个匹配结果,可自行调整取第一个匹配项即可 next(); }
内容的提问来源于stack exchange,提问作者Misbahu Abubakar
相关产品推荐
相关产品推荐

