统计字符串
- 统计一个字符串中字符出现的次数
- 获得次数最多的一个,共出现几次
- 用字典的方式
var string = 'hello world';
function statistics(string) {
var dictionaries = {
};
for (var i = 0; i < string.length; i++) {
if (dictionaries[string[i]] === undefined) {
dictionaries[string[i]] = 1;
} else {
dictionaries[string[i]] += 1;
};
};
return dictionaries;
};
console.log(statistics(string));
var max, count = 0;
for (var key in statistics(string)) {
if (statistics(string)[key] > count) {
max = key;
count = statistics(string)[key];
};
};
console.log(max, count);