javascript - 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
};
}
解决方案
减少时,总是返回累加器的新值。在您的情况下,您向前一个累加器添加一个值以获取新值。所以你应该总是取a
(累加器),并添加 0(b.position === something
是false, 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
推荐阅读
- javascript - 如何在本机反应中在控制台中显示整个对象
- outlook - AppleScript 更改 Outlook 签名
- ruby-on-rails - ActiveRecord 存在吗?缓存
- javascript - 我希望我的 html 网站以不同的语言加载
- r - bs_embed_popover 与闪亮仪表板
- java - ConcurrentSkipListMap 添加泛型类中定义的比较器
- python - 查找两个字符串模式之间的文本
- java - 可以将服务器配置为禁用自签名证书吗?
- java - Maven:创建依赖项的 uber jar
- marklogic - 是否可以在 MarkLogic 中对三元组执行变音符号、区分大小写/不区分大小写和通配符搜索?