js - most of the characters and the number of times to get the string appears

method one:

  /**
       * @param {String}str 只接受字符串类型
       * @return{JSON} key:出现最多字符, value:出现次数;  数组类型不是String类型,则返回空对象
       **/
    function getMax(str){
        let hash = {};
        let num = 0;
        let json = {}; //返回的对象
        //判断是否是字符串
        if(Object.prototype.toString.call(str) != "[object String]") {
            return json;
        }
        for(let i = 0; i < str.length; i++){
            if(hash[str[i]] === undefined){
                hash[str[i]] = 1
            }else{
                hash[str[i]]++
            }
        }
        for(let item in hash){
            if(num < hash[item]){
                num = hash[item]
                json = {"字符": item, "次数": hash[item]}
            }
        }
        return json;
    }

Guess you like

Origin www.cnblogs.com/sunidol/p/11512458.html