代碼以下:javascript
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>測試字符串中最多出現的字符</title> </head> <body> <div class="test"> <p>test string is: aaabbbcccdeeeff</p> </div> <script type="text/javascript"> var stringUtil = {}, max = 0; stringUtil.getMaxLengthCharacter = function(s) { var getObj, info = {}, getMaxLength; /* * 把字符和出現次數存放在對象中 */ getObj = (function(s) { var i = 0, j = s.length, obj = {}; for (i = 0; i < j; i++) { if (!obj[s[i]]) { obj[s[i]] = 1; } else { obj[s[i]] += 1; } } return obj; })(s); /* * 找出最長的個數 * 考慮到一個字符串中的最大長度可能不止一個,因此,這裏須要找出最大數 */ getMaxLength = (function() { var max = 0, //好歹也出現0次 i; for (i in getObj) { if (getObj[i] >= max) { max = getObj[i]; } } return max; })(); for (var i in getObj) { if (getObj[i] === getMaxLength) { info[i] = getObj[i]; } } return info; }; // 調用 var res = stringUtil.getMaxLengthCharacter('aaabbbcccdeeeff'); window.console && console.log(res); </script> </body> </html>