Vue过滤含空属性对象数组报错,如何在return中添加if判断?
嘿,这个坑我之前踩过好几次!当过滤数组里的对象时,一旦碰到price这类属性为null或undefined的情况,直接访问就会抛出TypeError,整个筛选逻辑直接崩掉。不过有几个简单的方案能完美解决这个问题,咱们一步步来看:
方案1:在过滤条件里显式做空值检查
最直接的办法就是在判断属性前,先确认它不是null或undefined。比如你原来的过滤逻辑可能是这样的(会报错的版本):
const filteredGames = allGames.filter(game => { return game.name.includes(searchTerm) && game.venue === selectedVenue && game.price <= maxPrice; // 这里如果game.price是null就会炸 });
现在修改成带空值检查的版本,根据你的业务需求选择两种处理方式:
方式A:排除属性为空的对象
如果你不想让price为空的游戏出现在筛选结果里,就先判断属性存在再做比较:
const filteredGames = allGames.filter(game => { const matchesSearch = game.name.includes(searchTerm); const matchesVenue = game.venue === selectedVenue; // 先确认price不是null/undefined,再判断价格条件 const matchesPrice = game.price !== null && game.price !== undefined && game.price <= maxPrice; return matchesSearch && matchesVenue && matchesPrice; });
方式B:保留属性为空的对象
如果price为空的游戏应该通过价格筛选(比如默认视为符合条件),就把空值情况单独列出来:
const filteredGames = allGames.filter(game => { const matchesSearch = game.name.includes(searchTerm); const matchesVenue = game.venue === selectedVenue; // price为空时直接通过,否则判断价格条件 const matchesPrice = game.price === null || game.price === undefined || game.price <= maxPrice; return matchesSearch && matchesVenue && matchesPrice; });
方案2:用可选链+空值合并运算符简化判断
现代JS里的可选链?.和空值合并??能让代码更简洁。比如你可以给空属性设置一个默认值,再进行比较:
const filteredGames = allGames.filter(game => { const matchesSearch = game.name?.includes(searchTerm) ?? true; // 如果name也可能为空,默认通过搜索 const matchesVenue = game.venue === selectedVenue; // price为空时设为-Infinity(肯定小于任何maxPrice),这样会保留这类对象 const matchesPrice = (game.price ?? -Infinity) <= maxPrice; return matchesSearch && matchesVenue && matchesPrice; });
这里的game.price ?? -Infinity意思是:如果game.price是null或undefined,就用-Infinity代替,这样不管用户设置的maxPrice是多少,-Infinity <= maxPrice都会是true,从而保留这些对象。如果你想排除它们,就把默认值改成Infinity,这样Infinity <= maxPrice只有当maxPrice也是无穷大时才成立,相当于排除空值对象。
方案3:提前标准化数据(推荐长期维护)
如果你的数组里经常出现属性为空的情况,最好提前做一次数据标准化,给空属性设置合理的默认值,之后的筛选逻辑就不用每次都做空值检查了:
// 先把所有game的price标准化,空值设为0或者你需要的默认值 const normalizedGames = allGames.map(game => ({ ...game, price: game.price ?? 0, // 空值设为0 venue: game.venue ?? '未知场地' // 其他属性也可以一起处理 })); // 之后直接用标准化后的数组筛选,不用再担心空值问题 const filteredGames = normalizedGames.filter(game => { return game.name.includes(searchTerm) && game.venue === selectedVenue && game.price <= maxPrice; });
这个方案能让后续的筛选逻辑更干净,尤其适合大型项目或者需要多次筛选的场景。
核心思路就是:永远不要直接访问可能为null/undefined的对象属性,要么提前检查,要么提前给默认值,这样就能避免TypeError,让筛选逻辑稳定运行。
内容的提问来源于stack exchange,提问作者pharaohlxvi

