js 统计字符串中出现次数最多的字符?

时间:2022-08-27 15:17:41
 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script> var s="aaaabbbbssssssss";
var fres={}; //用来记录所有的字符的出现频次
var mostFreqChar=''; //用来记录最大频次的字符
for(var i=0;i<s.length;i++){
var char=s[i];
if(!fres[char]){
fres[char]=0;
} fres[char]++;
if(mostFreqChar==''||fres[char]>fres[mostFreqChar]){
mostFreqChar=char;
} }
console.log(mostFreqChar);
console.log(fres[mostFreqChar]); </script>
</head>
<body> </body>
</html>