遍历对象统计所有数组中指定字符串的出现次数
问题排查与修正
你的代码核心问题在于遍历逻辑错误: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
相关产品推荐
相关产品推荐

