js判断字符串中出现次数最多的字符

var str = 'bbddcfhhh';
var json = {};
for(var i = 0; i < str.length; i++){
    if (!json[str.charAt(i)]) {
        json[str.charAt(i)] = 1;
    } else {
        json[str.charAt(i)]++;
    }
}
var count = 0;
var arr = [];
for(var key in json){
    if(json[key] > count){
        count = json[key];
    }
    //考虑次数相同的情况,次数作为数组索引
    if(json[key] == count){
        if(arr[count] != undefined){
            arr[count] +=','+ key;
        }
        else{
            arr[count] = key;
        }
    }
}
console.log('出现最多的值是'+arr[arr.length-1]+'出现次数为'+ (arr.length-1));

猜你喜欢

转载自blog.csdn.net/qq_36367995/article/details/80264391