统计每个元素出现的次数, 例如["b", "c","b", "c","a", "b", "c"] ---> {a:1,b: 3, c:

98 阅读1分钟

使用数组的reduce方法

题目1.
const arr = ["b", "c","b", "c","a", "b", "c"] 
const obj = {}
let c =arr.reduce((total,item)=>{

 // total的初始值是个空对象 , 
 
    if(total[item]){      如果total有item这个元素 让他的值+1
        total[item]++
    }else{                   
        total[item]=1     如果没有这个item属性,就赋予它这个属性并且值为1
    }
    return total

    },{})
    console.log(c);  //{b: 3, c: 3, a: 1}
    ```
    
    
    题目二
    ```
    var arr = [{ label: '男', value: 1 }, { label: '女', value: 0 }]

    let c =arr.reduce((total,item)=>{
            
            total[item.value]=item.label
            return  total

    },{})

    console.log(c)   // {0: "女", 1: "男"}