食谱作者匹配JS代码报错排查及逻辑优化咨询
食谱作者匹配功能报错及逻辑修正
问题描述
我需要实现根据searchArray中的作者信息匹配食谱数组cakeRecipes中的食谱。searchArray是包含作者数组的对象,食谱以对象形式存储在数组中。我的思路是将数组转为字符串并统一转为toLowerCase(),尝试匹配至少一位符合条件的作者:仅搜索名字时模糊匹配含该名字的作者;搜索全名(含空格)时需精确匹配。但运行代码时出现报错:
TypeError: Cannot read properties of null (reading 'toLowerCase') at /home/runner/JS-module-7-assignment-cake-search/index.js:59:33 at Array.filter (<anonymous>) at searchRecipeWithAuthor (/home/runner/JS-module-7-assignment-cake-search/index.js:57:39) at Object.<anonymous> (/home/runner/JS-module-7-assignment-cake-search/index.js:77:13) at Module._compile (node:internal/modules/cjs/loader:1101:14)
报错指向const recipeAuthor = Author.toLowerCase();行,虽此前用console.log可正常输出小写作者名,但仍无法继续测试,同时怀疑自身逻辑或代码写法存在问题,相关代码如下:
const searchRecipeWithAuthor = (searchArray) => { const { authors } = searchArray; const searchAuthor = authors.toString().toLowerCase(); // console.log(searchAuthor); // tested and works const matchingRecipes = cakeRecipes.filter(({ Author}) => { // console.log(Author)); // gives all Authors as string const recipeAuthor = Author.toLowerCase(); // console.log(recipeAuthor); // tested and works if (searchAuthor.includes(" ")) { // console.log(searchAuthor); // tested and works if (searchAuthor === recipeAuthor) { // can't test from this part, dus to TypeError referencing const recipeAuthor = //Author.toLowerCase(); Cannot read properties of null (reading 'toLowerCase') return true; } else { if (recipeAuthor.includes(searchAuthor)) { return true; } } } }); return matchingRecipes.map((recipe) => recipe[0]); }; console.log(searchRecipeWithAuthor(searchParams));
解决方案
1. 先解决报错问题
报错原因是cakeRecipes中存在某个食谱的Author字段为null或undefined,调用toLowerCase()时触发类型错误。需要先做空值和类型校验:
// 处理空值,确保转小写前是有效字符串 const recipeAuthor = typeof recipe.Author === 'string' ? recipe.Author.toLowerCase().trim() : '';
2. 修正核心匹配逻辑
原代码存在三个关键问题:
- 仅处理了搜索内容带空格的场景,未覆盖无空格的模糊匹配
- 将作者数组转为字符串的方式错误(如
['John','Jane']会变成"john,jane"),无法分别匹配单个作者 - 最后
map(recipe => recipe[0])属于错误操作,食谱本身是对象而非数组
修正后的完整代码:
const searchRecipeWithAuthor = (searchArray) => { const { authors } = searchArray; // 将每个搜索作者转成小写并去空格,存入数组方便逐个匹配 const targetAuthors = authors.map(author => author.toLowerCase().trim()); return cakeRecipes.filter(recipe => { // 安全处理食谱作者字段 const recipeAuthor = typeof recipe.Author === 'string' ? recipe.Author.toLowerCase().trim() : ''; // 遍历目标作者,只要有一个匹配就保留该食谱 return targetAuthors.some(target => { if (target.includes(' ')) { // 搜索内容含空格,执行精确匹配 return target === recipeAuthor; } else { // 搜索内容无空格,执行模糊匹配 return recipeAuthor.includes(target); } }); }); }; console.log(searchRecipeWithAuthor(searchParams));
3. 逻辑说明
- 提前将所有搜索作者转为小写并去空格,避免重复转换操作
- 对食谱作者字段做严格类型校验,彻底杜绝空值报错
- 使用
Array.some()方法实现"匹配至少一位作者"的需求,逻辑更清晰 - 明确区分带空格(全名)的精确匹配和无空格(单名)的模糊匹配规则
- 移除错误的数组索引取值,直接返回过滤后的食谱对象数组
内容的提问来源于stack exchange,提问作者Sahdia
相关产品推荐
相关产品推荐

