2021-8-30
/**
* 统计字符串内出现最多的字符,并记录该字符的个数,若出现相同次数,则返回第一个遇到的个数最多的字符。
* @param {string}} str
*/
function getChar(str){
let obj = {}; // 通过给对象添加属性记录字符串中的所有字符
let max = {char:'',count:-1}; // 记录出现最多的字符以及它的次数
// 循环字符串,若字符串中某一个字符没被记录,则给obj添加属性,并且记录出现次数为1,若已经出现过,则出现次数加一
for(let i = 0;i<str.length;i++){
if(obj.hasOwnProperty(str[i])){
obj[str[i]]++;
}else{
obj[str[i]] = 1;
}
}
// 循环obj对象,查询出现次数最多的字符
for(let item in obj){
if(obj[item] > max.count){
max.char = item;
max.count = obj[item]
}
}
// 返回最多的字符
return max;
}
console.log(getChar("abbccccdb")); //{ char: 'c', count: 4 }