JS算法——统计字符数量
2018-05-29 本文已影响0人
南方小小姑娘
function charCount( str ) {
var obj = {},
len = str.length,
i = 0;
for ( ; i < len; i++ ) {
var val = str.charAt(i);
if ( obj[val] && obj[val].value === val ) {
obj[val].count++;
}
else {
obj[val] = {};
obj[val].count = 1;
obj[val].value = val;
}
}
for ( var key in obj ) {
console.log( key + ' is ' + obj[key].count );
}
return obj;
}