统计一个数组或者一个字符串中每个值出现的次数
常规for循环
var egFor = function(strArr){
const chars = {};
for(let i=0;i<strArr.length;i++){
const ch = strArr[i];
if(!chars[ch]){
chars[ch] = 0;
}
chars[ch]++;
// chars[ch] = (chars[ch] +1 ) || 1;
}
return chars;
}
console.log(egFor('abababababaababba'));
//{a: 9, b: 8}
console.log(egFor([1,2,3,4,5,6,7,3,32,2,21,2]));
//{1: 1, 2: 3, 3: 2, 4: 1, 5: 1, 6: 1, 7: 1, 21: 1, 32: 1}
reduce()方法 不能用于字符串 可以将字符串转为数组在使用reduce()方法
var egReduce = function(strArr){
const arrStr = strArr;
return arrStr.reduce(function(prev,next){
// console.log("prev:",prev);
// console.log("next:",next);
prev[next] = (prev[next]+1) || 1;
return prev;
},{});
}
console.log(egReduce([1,2,3,4,5,6,7,3,32,2,21,2]));
//{1: 1, 2: 3, 3: 2, 4: 1, 5: 1, 6: 1, 7: 1, 21: 1, 32: 1}