ES6使用reduce求用户(credits+shots)最大值遇undefined问题求助
解决reduce查找(credits + shots)最高用户返回undefined的问题
嘿,我来帮你搞定这个reduce的问题!你遇到的返回undefined的情况,大概率是因为初始值设置错误或者没有正确计算总和并比较导致的,咱们一步步理清楚:
先看错误的常见原因
你之前尝试添加初始值却无效,很可能是给的初始值不符合用户对象的结构——比如你用了{}或者0当初始值,这样第一次迭代时prev.credits或prev.shots会是undefined,undefined和数字相加会得到NaN,而NaN和任何数值比较都会返回false,直接打乱了reduce的逻辑,最后就可能返回undefined。
正确的实现方式
假设你的用户数组是这样的:
const users = [ { name: 'Alice', credits: 100, shots: 20 }, { name: 'Bob', credits: 80, shots: 30 }, { name: 'Charlie', credits: 120, shots: 15 } ];
方式1:数组非空时,无需初始值
如果能确定用户数组永远不为空,直接用reduce就行,每次迭代计算当前用户和上一个用户的总和并比较:
const topUser = users.reduce((prev, current) => { // 分别计算两个用户的credits+shots总和 const prevTotal = prev.credits + prev.shots; const currentTotal = current.credits + current.shots; // 比较总和,返回较大的那个用户对象 return prevTotal > currentTotal ? prev : current; }); console.log(topUser); // 输出 { name: 'Charlie', credits: 120, shots: 15 }
方式2:数组可能为空时,设置合法初始值
如果数组有可能是空的,必须给reduce设置一个包含credits和shots属性的初始对象,避免出现NaN的问题:
const topUserWithInitial = users.reduce((prev, current) => { const prevTotal = prev.credits + prev.shots; const currentTotal = current.credits + current.shots; return prevTotal > currentTotal ? prev : current; }, { name: '默认用户', credits: 0, shots: 0 }); // 初始值确保有合法的credits和shots console.log(topUserWithInitial); // 数组非空时返回Charlie,为空时返回初始对象
避坑提醒
- 绝对不要用空对象
{}或者数字0当初始值,这会导致访问prev.credits时得到undefined,计算总和变成NaN,逻辑直接失效。 - 每次迭代一定要明确计算
credits + shots的总和,不要直接比较单个属性,这是你需求的核心。
内容的提问来源于stack exchange,提问作者Miguel Stevens
相关产品推荐
相关产品推荐

