js-检测字符串出现次数最多,并返回

function validateStr(val){
    let obj = {};
    let maxNum = -1;
    let maxStr;
    for(let i=0;i<val.length;i++){
        if(!obj[val[i]]){
            obj[val[i]] = 1;
            if( obj[val[i]]>maxNum){
                maxNum = obj[val[i]];
                maxStr = val[i];
            }
        }else{
            obj[val[i]]++;
            if( obj[val[i]]>maxNum){
                maxNum = obj[val[i]];
                maxStr = val[i];
            }
        }
    }
    return{
        maxNum,
        maxStr
    }
}

 

posted @ 2018-12-20 21:34  面包_girl  阅读(284)  评论(0编辑  收藏  举报
/* 鼠标点击文字特效 */