统计字符串中出现最多的字符和次数(重点)
// 统计字符串中出现最多的字符和次数
let str = "abcabcdfraaaa";
let k = {};//定义一个空对象:用于保存字符串中字符及统计该字符出现的次数
for (let i = 0; i < str.length; i++) {
let chars = str.charAt(i);//将下标为i的字符取出赋给变量chars
if (k[chars]) {//若对象k中存在属性chars(chars变量代表某个字符)
k[chars]++;
} else {//对象k中不存在属性chars(chars变量代表某个字符)
k[chars] = 1;
}
}
console.log("k=", k);
console.log(k.chars);
let max = 0;
let ch = '';
//遍历对象的属性:for...in循环
for (let t in k) {
if (k[t] > max) {
max = k[t];
ch = t;
}
}
console.log(`出现次数最多的字母是:${ch},出现了${max}次`);
let max = 0
let ch = ''
for(let t in k){ //t='a',k[t]<=>k['a']<=>k.'a' == 1
if(k[t]>max){
max = k[t] //max = a
ch = t //ch = 'a'
}
}
console.log(`出现次数最多的字母是${ ch } :${ max }`)