<script> //题目:统计出现最多的字符,并统计次数 let str = "aaaabbbccccdddddddd" var obj = {} //1.统计次数 for (var i = 0; i < str.length; i++) { var char = str[i] if (obj[char]) { //如果有就加1 obj[char]++ } else { //没有就设值为1 obj[char] = 1 } } //2.拿到字符的最大出现次数 var max=0; for(var key in obj ){ if(max < obj[key]){ max=obj[key] } } //3.拿到最大次数对应的字符 for(var key in obj){ if(obj[key]==max){ console.log('出现次数最多的是:'+key) console.log('总共出现次数为:'+max) } } </script>
标签:面试题,obj,max,js,char,次数,key,var From: https://www.cnblogs.com/Ynline/p/16624427.html