JavaScript reducer中&&运算符导致数值重置该如何解决?
问题原因
你代码的问题出在reduce回调函数的返回值逻辑上:&&运算符会在左侧条件不成立时直接返回左侧的布尔值false,而非你预期的累计值a。当遍历到非对应position的元素时,回调返回false,下一轮遍历的累计值a就会被赋值为false,后续运算时false会被隐式转换为0,就出现了统计值被重置的问题。
修正方案
方案1:直接修改原有reduce逻辑
把&&替换为三元运算符,条件不匹配时直接返回原累计值即可:
const totalGK = get(team).reduce( (a, b) => b.position === "GK" ? a + b.qty : a, 0 ); const totalDef = get(team).reduce( (a, b) => b.position === "Def" ? a + b.qty : a, 0 ); const totalMid = get(team).reduce( (a, b) => b.position === "Mid" ? a + b.qty : a, 0 ); const totalAtt = get(team).reduce( (a, b) => b.position === "Att" ? a + b.qty : a, 0 ); return { totalGK, totalDef, totalMid, totalAtt };
方案2:优化为单次遍历统计所有值
现有写法会对team数组遍历4次,你可以改成一次遍历就完成所有position的统计,性能更好:
const positionStats = get(team).reduce((acc, curr) => { const { position, qty } = curr; if (position === 'GK') acc.totalGK += qty; else if (position === 'Def') acc.totalDef += qty; else if (position === 'Mid') acc.totalMid += qty; else if (position === 'Att') acc.totalAtt += qty; return acc; }, { totalGK: 0, totalDef: 0, totalMid: 0, totalAtt: 0 }); return positionStats;
内容的提问来源于stack exchange,提问作者thorntj85
相关产品推荐
相关产品推荐

