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

遍历对象统计所有数组中指定字符串的出现次数

问题排查与修正

你的代码核心问题在于遍历逻辑错误:festivals[festival]拿到的是每个用户对应的数组,直接和字符串target做全等比较永远不会成立,所以计数一直为0。要实现需求,需要先遍历对象的每个数组,再统计数组内目标字符串的出现次数并累加。

修正方案1:嵌套循环实现

const festivals = {
  'Danny': ['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Benicassim','MadCool'],
  'Jimbo': ['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Leeds','Benicassim','MadCool'],
  'Richard': ['Glastonbury','Leeds','Leeds','Benicassim','MadCool'],
  'John': ['Glastonbury','Leeds']
}

let totalFestivals = 0
let target = 'Benicassim'

// 遍历对象中每个用户的节日数组
for (let person in festivals) {
  const arr = festivals[person];
  // 遍历当前数组的每个元素
  for (let item of arr) {
    if (item === target) {
      totalFestivals++;
    }
  }
}
console.log(totalFestivals); // 输出3

修正方案2:用数组方法简化代码

利用Object.values()提取所有数组,再通过reduce和filter快速累加次数:

const festivals = {
  'Danny': ['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Benicassim','MadCool'],
  'Jimbo': ['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Leeds','Benicassim','MadCool'],
  'Richard': ['Glastonbury','Leeds','Leeds','Benicassim','MadCool'],
  'John': ['Glastonbury','Leeds']
}

const target = 'Benicassim';
const totalFestivals = Object.values(festivals).reduce((total, arr) => {
  return total + arr.filter(item => item === target).length;
}, 0);

console.log(totalFestivals); // 输出3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:36:00