const arr = ["b", "c","b", "c","a", "b", "c"]
const obj = {}
// 你的代码 ...console.log(obj) // ==> {a:1, b: 3, c: 3}
这里我写出了两种方法
第一种方法:forEach代码如下
// 第一种方法(forEach)
var arr = ['a', 'b', 'c', 'b', 'a', 'f', 'b']
var obj = {}
arr.forEach(item => {
obj[item] ? obj[item]++ : obj[item] = 1;
})
console.log(obj);
// 打印结果 {a: 2, b: 3, c: 1, f: 1}
第二种方法: reduce代码如下
// 第二种方法 (reduce)
var arr = ['a', 'b', 'c', 'b', 'a', 'f', 'b']
var obj = arr.reduce((obj, item) => {
obj[item] ? obj[item]++ : obj[item] = 1;
return obj
}, {})
console.log(obj);
// 打印结果: {a: 2, b: 3, c: 1, f: 1}