[“b”, “c”,”b”, “c”,”a”, “b”, “c”] 统计每个元素出现的次数
方法1: reduce
const arr = ["b", "c","b", "c","a", "b", "c"]
const newList = arr.reduce((acc,item)=>{
if(item in acc) { // 看item有没有在acc里面
acc[item]++
} else {
acc[item] = 1
}
return acc
},{})
console.log(newList);
输出结果:

方法2: forEach
const arr = ["b", "c","b", "c","a", "b", "c"]
const obj = {}
arr.forEach(item => {
// if(obj[item]) {
// obj[item] ++
// } else {
obj[item] = 1
// }
obj[item] ? obj[item] ++ : obj[item] =1
})
consloe.log(obj)
输出结果:
