//方法1 function getLetterTimes(str){ for(var i = 0,hash = {}; i < str.length; i++){ if(hash[str[i]]){ hash[str[i]]++; }else{ hash[str[i]]=1; } } return hash; } var str = "helloworld"; console.dir(getLetterTimes(str));
//方法2 function getLetterTimes(str){ var arr=str.split("") .sort() .join("") .match(/([a-z])\1*/g) .sort(function(a,b){ return b.length-a.length; }); console.log("出现最多的字母是: "+arr[0][0]+",共"+arr[0].length+"次"); var hash = {}; arr.forEach(function(val){ hash[val[0]] = val.length; }); return hash; } var str = "helloworld"; console.dir(getLetterTimes(str));
//方法3 function getMaxNumberOfChar(str) { return (str + '').split('').reduce(function(pre, cur, index, arr) { cur in pre ? pre[cur]++ : (pre[cur] = 1); pre[cur] > pre.value && (pre.char = cur, pre.value = pre[cur]); return pre; }, {value: 0}); } var result = getMaxNumberOfChar('helloworld'); console.log(result);
//方法4 function getMaxNumberOfChar(str) { return (str + '').split('').sort().join('').match(/(\w)\1*/g).reduce(function(pre, cur) { return cur.length > pre.value ? {value: cur.length, char: cur[0]} : pre; }, {value: 0}) } var result = getMaxNumberOfChar('helloworld'); console.log(result);