You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:54:03