代码如下:
<!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>