原搜索返回'Mission Impossible',修改list后为空,如何用list搜索genre数组得'The Mummy'?
如何调整搜索数组以返回'The Mummy'
嘿,我来帮你搞定这个问题!首先对齐一下常见的场景——我先模拟一个符合你描述的代码结构,这样更容易讲清楚怎么调整。
假设你的电影数据结构大概是这样的:
const movies = [ { title: 'Mission Impossible', genre: ['Action', 'Thriller'] }, { title: 'The Mummy', genre: ['Adventure', 'Fantasy'] }, // 其他电影条目... ];
原来的情况为什么返回'Mission Impossible'?
你之前的搜索逻辑大概率是匹配list数组中任意一个类型的电影,比如当时的list是['Action'],代码大概长这样:
const originalList = ['Action']; const result = movies .filter(movie => movie.genre.some(genre => originalList.includes(genre))) .map(movie => movie.title); // 输出: ['Mission Impossible']
为什么修改list后返回空数组?
这说明你新修改的list里的类型,没有任何一部电影的genre数组包含它。比如如果你改成了['Drama'],自然找不到匹配的电影。
怎么调整才能返回'The Mummy'?
核心就是让list里的类型能精准匹配到'The Mummy'的genre,同时避开'Mission Impossible'的类型(如果只想要这一个结果的话)。分两种常见情况:
情况1:匹配list中任意一个类型
只要让list包含'The Mummy'的任意一个genre就行,比如:
const targetList = ['Adventure']; const desiredResult = movies .filter(movie => movie.genre.some(genre => targetList.includes(genre))) .map(movie => movie.title); // 输出: ['The Mummy']
情况2:必须匹配list中所有类型
如果你的搜索逻辑是要求电影包含list里的所有类型,那就要让list完全对应'The Mummy'的genre子集,比如:
const targetList = ['Adventure', 'Fantasy']; const desiredResult = movies .filter(movie => targetList.every(genre => movie.genre.includes(genre))) .map(movie => movie.title); // 输出: ['The Mummy']
额外注意点
别忽略大小写和空格!如果你的genre字符串大小写不一致(比如list里是'adventure',但电影里是'Adventure'),会直接匹配失败。这时候可以统一转成小写再比较:
const targetList = ['adventure']; const desiredResult = movies .filter(movie => movie.genre.some(genre => genre.toLowerCase() === targetList[0].toLowerCase())) .map(movie => movie.title); // 输出: ['The Mummy']
内容的提问来源于stack exchange,提问作者Broseph
相关产品推荐
相关产品推荐

