// 方法1 通过key-value
function getMaxCount1(str) {
let json = {};
let result = '';
for(let i = 0; i < str.length; i++) {
let char = str[i];
if (!json[char]) {
json[char] = 1
}else {
json[char]++;
}
}
// 存储次数出现最多的值和出现的次数
var maxCountChar = '';
var maxCount = 0;
// 遍历json找出出现最多的值
for(var key in json) {
if(json[key] > maxCount) {
maxCount = json[key];
maxCountChar = key;
}
}
return `出现最多的值是${maxCountChar}出现最多的次数为${maxCount}`;
}
console.log(getMaxCount1('sdsfsdsdsss'));
// 方法2 通过key-value,运算有所差别。
// (1) 先把字符串转换成数组,对数组进行一次遍历。
// (2) 在遍历的过程中,判断json对象中是否有相应的key
function getMaxCount2(str) {
var json = {};
var maxCount = 0, maxCountChar = '';
str.split('').forEach(item => {
// 判断json对象中是否有相应的key
if (!json.hasOwnProperty(item)){
// 当前字符出现的次数, 'bsad'.split('s')= ["b","ad"]
// console.log('bsgsad'.split('s')) = ["b","g","ad"]
var number = str.split(item).length - 1;
if(number > maxCount) {
// 写入json对象
json[item] = number;
maxCount = number;
maxCountChar = item;
}
}
})
return `出现最多的值是${maxCountChar}出现最多的次数为${maxCount}`;
}
console.log(getMaxCount2('adasfdsfds'))
console