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

如何在单次循环中根据条件递增对象中的多个计数项?

用reduce实现单次遍历的简洁统计

你可以用Array.reduce来完成这个需求,只遍历数组一次就能完成所有计数器的更新,代码更紧凑且逻辑清晰:

const totals = myArr.reduce((acc, val) => {
  if (val.condition1) acc.a++;
  if (val.condition2 || val.condition3) acc.b++;
  // 若有其他统计规则,直接在此处添加即可
  return acc;
}, { a: 0, b: 0, c: 0 });

说明

  • reduce的初始值就是我们需要的计数器对象,避免了先声明变量再修改的冗余操作。
  • 每次遍历数组元素时,根据对应的布尔属性直接更新累加器acc的对应字段,全程只遍历myArr一次。

如果后续统计规则较多,还可以把规则抽成配置数组,让代码更易维护:

// 定义统计规则:条件属性名 -> 对应计数器字段
const countRules = [
  { condition: 'condition1', target: 'a' },
  { condition: 'condition2', target: 'b' },
  { condition: 'condition3', target: 'b' },
];

const totals = myArr.reduce((acc, val) => {
  countRules.forEach(rule => {
    if (val[rule.condition]) acc[rule.target]++;
  });
  return acc;
}, { a: 0, b: 0, c: 0 });

这种方式下,修改统计规则只需调整countRules数组,无需改动遍历逻辑,同样只遍历myArr一次(内部遍历规则数组是固定次数,和目标数组长度无关)。

内容的提问来源于stack exchange,提问作者jn025

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:40:31