var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice','amy','amy','marry'];
// 利用 for in 遍历对象的方式实现
function ll(arr){
var aa = {};
for(var i = 0;i<arr.length;i++){
if(arr[i] in aa){
aa[arr[i]] += 1;
}else{
aa[arr[i]] = 1;
}
}
return aa;
}
console.log('222',ll(names)) //{"Alice": 2, "Bob": 1, "Tiff": 1,"Bruce": 1, "amy": 2,"marry": 1 }
// 利用Object.hasOwnProperty('属性')来实现
function mm(arr){
var aa = {};
for(var i = 0;i<arr.length;i++){
if(aa.hasOwnProperty(arr[i])){
aa[arr[i]] += 1;
}else{
aa[arr[i]] = 1;
}
}
return aa;
}
console.log('333',mm(names)) //{"Alice": 2, "Bob": 1, "Tiff": 1,"Bruce": 1, "amy": 2,"marry": 1 }
// 利用 reduce()高阶函数来实现
var ff = names.reduce((calc,item) => {
if(item in calc){
calc[item] += 1;
}else{
calc[item] = 1;
}
return calc
},{})
console.log(ff,'123') //{"Alice": 2, "Bob": 1, "Tiff": 1,"Bruce": 1, "amy": 2,"marry": 1 }