首页 > 解决方案 > Javascript reducer,如何停止 && 运算符重置值?

问题描述

这里是业余编码员,reducers 的新手。

我有一个将对象添加到数组中的应用程序,其中包含捕获每个对象位置值的数量的减速器。

下面在一定程度上起作用,当我添加两个“Att”实体时,totalAtt 的数量等于两个,但是当我添加另一个位置值时,totalAtt 的数量重置为零。对于所有位置值也是如此。

鉴于其布尔性质,发现 && 运算符将我的初始值重置为 false。

任何人都知道如何调整代码以捕获数量而不重置值?

    const totalGK = get(team).reduce(
        (a, b) => b.position === "GK" && a + b.qty,
        0
    );
    const totalDef = get(team).reduce(
        (a, b) => b.position === "Def" && a + b.qty,
        0
    );
    const totalMid = get(team).reduce(
        (a, b) => b.position === "Mid" && a + b.qty,
        0
    );
    const totalAtt = get(team).reduce(
        (a, b) => b.position === "Att" && a + b.qty,
        0
    );

    return {
        totalGK,
        totalDef,
        totalMid,
        totalAtt
    };
}

标签: javascriptarraysreactjsobjectreducers

解决方案


减少时,总是返回累加器的新值。在您的情况下,您向前一个累加器添加一个值以获取新值。所以你应该总是取a(累加器),并添加 0(b.position === somethingfalse, so it's casted to 0)或如果条件是数字true

const totalGK = get(team).reduce(
  (a, b) => a + (b.position === "GK" && b.qty),
  0
);
const totalDef = get(team).reduce(
  (a, b) => a + (b.position === "Def" && b.qty),
  0
);
const totalMid = get(team).reduce(
  (a, b) => a + (b.position === "Mid" && b.qty),
  0
);
const totalAtt = get(team).reduce(
  (a, b) => a + (b.position === "Att" && b.qty),
  0
);

但是,有一种更短、更易读的方法来解决这个问题,将 减少team到一个对象,使用position值作为键,并将 添加qty到键的前一个值。要获取 const,请解构 reduce 创建的对象,并使用 0 作为默认值。

例子:

const get = arr => arr;

const team = [{ position: 'GK', qty: 2 }, { position: 'GK', qty: 2 }, { position: 'GK', qty: 2 }, { position: 'Att', qty: 3 }, { position: 'Att', qty: 3 }, { position: 'Att', qty: 3 }];

const {
  GK: totalGK = 0,
  Def: totalDef = 0,
  Mid: totalMid = 0,
  Att: totalAtt = 0,
} = get(team).reduce((acc, obj) => ({
  ...acc,
  [obj.position]: (acc[obj.position] || 0) + obj.qty
}), {});

console.log(totalGK); // 6
console.log(totalDef); // 0
console.log(totalMid); // 0
console.log(totalAtt); // 9


推荐阅读