js 统计字符串中出现次数最多的字符?
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <script> 7 8 var s="aaaabbbbssssssss"; 9 var fres={}; //用来记录所有的字符的出现频次 10 var mostFreqChar=''; //用来记录最大频次的字符 11 for(var i=0;i<s.length;i++){ 12 var char=s[i]; 13 if(!fres[char]){ 14 fres[char]=0; 15 } 16 17 fres[char]++; 18 if(mostFreqChar==''||fres[char]>fres[mostFreqChar]){ 19 mostFreqChar=char; 20 } 21 22 } 23 console.log(mostFreqChar); 24 console.log(fres[mostFreqChar]); 25 26 </script> 27 </head> 28 <body> 29 30 </body> 31 </html>