js 统计一个字符串中出现的字符最多的字符

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>统计一个字符串中出现的字符最多的字符</title>
<script>
    window.onload = function(){
        var str = 'asdfssaaasasasasaa';
        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 key = 0;
        var iMax = 0;
        for(var attr in json){
            if(json[attr] >iMax){
                iMax = json[attr];
                key = attr;
            }
        }
        alert("出现最多次数的是:"+key+",value:"+iMax);
        
    };
</script>
</head>


<body>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/moon-yyl/p/9237123.html
今日推荐