js finds the character and the number of occurrences of the string most times

method one

        Get the character and number of objects first, then count the maximum value in the object, and finally compare the maximum value.

<script>
    var str = 'aabbbcccccdddddddd';
    var obj = {}; //创建一个对象
    for(var i=0;i<str.length;i++){//每一个字符都要知道次数,所以要循环
        var char = str.charAt(i);//返回指定索引处的字符
        if(obj[char]){
            obj[char]++
        }else{
            obj[char] = 1;
        }
    }
     console.log(obj);//{a:2,b:3,c:5,d:8}
     //统计出来最大值
     var max = 0;
     for(var key in obj){
        if(max<obj[key]){
            max = obj[key];
        }
     }
     console.log(max);//8
     //拿最大值去对比
     for(var key in obj){
        if(obj[key] == max){
            console.log('最多的字符是' + 'key');//d
            console.log('出现的次数是' + 'max');//8
        }
     }
</script>

Method Two

        First get the character with the most number of times and the variable of the number of times, sort the original string (the string is converted into an array, and the array is sorted and then converted into a string), and the regular pattern matches the repeated content, and then judges.

 <script>
        //需求:判断一个字符串中出现次数做多的字符,并统计次数
        //出现次数最多的字符的变量
        var value = '';
        // 出现的次数的变量
        var index = 0;
        //原始字符串改为计算好的字符串(排序)
        var str = 'avsgsgehdgyydgyyyyesnnngs';
        //字符串转换为数组
        var arr = str.split('');
        //数组进行排序再改为字符串
        var str = arr.sort().join('');
        //正则匹配到了重复内容
        var reg = /(\w)\1+/g;
        //判断
        str.replace(reg,function(val,item){
            if(index<val.length){
                index = val.length;
                value = item;
            }
        })
        console.log('出现次数做多的字符是:'+value,'出现的次数是:'+index);
    </script>

Guess you like

Origin blog.csdn.net/m0_73460278/article/details/126988175