var str = "stiabsstringapbs";
var obj = {};
for (var i = 0; i < str.length; i++) {
var key = str[i];
if (!obj[key]) {
obj[key] = 1;
} else {
obj[key]++;
}
}
var max = -1;
var max_key = "";
var key;
for (key in obj) {
if (max < obj[key]) {
max = obj[key];
max_key = key;
}
}
alert("max:"+max+" max_key:"+max_key);
var str = "stiabsstringapbs"; //定义字符串
var obj = {}; //定义对象
for (var i = 0; i < str.length; i++) { //遍历字符串
var key = str[i]; //存储字符
if (!obj[key]) { //若对象中不存在该key,初始化为1
obj[key] = 1;
} else { //若对象中存在该key,则数值加1
obj[key]++;
}
}
/*第一个for循环结束得到每个字符数量的对象,大概下面这鸟样
obj={
s:4,
t:2,
i:2,
...
}*/
var max = -1; //初始化最大数量,最大数量字符
var max_key = "";
var key;
for (key in obj) { //遍历obj对象,获得字符最大数量及对应字符
if (max < obj[key]) {
max = obj[key];
max_key = key;
}
}
alert("max:"+max+" max_key:"+max_key);
计算一篇英文文章中出现次数最多的单词以及出现次数
let input = 'hello how are you I am fine thank you'
let arr = input.split(' ');
let sum = {};
let res = '';
let max = 0;
for (let item of arr) {
if(sum[item] === undefined){
sum[item]=0;
}
sum[item]++;
}
for (let item in sum) {
if (sum[item] > max) {
res = item;
max = sum[item];
}
}
console.log(res);