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

时间:2023-03-09 00:48:13
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>