charAt(i)用来接受字符串中的每个字符:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
sumMax();
function sumMax() {
var str = prompt('请输入一串字符:');
var ob = {};
for (var i = 0; i < str.length; i++) {
var chars = str.charAt(i);
if (ob[chars]) {
ob[chars]++;
} else {
ob[chars] = 1;
}
}
console.log(ob);
var max = 0;
var ch = '';
//k是属性名,ob[k]是属性值
for (k in ob) {
if (ob[k] > max) {
max = ob[k];
ch = k;
}
}
alert(ch + '出现的次数最多,且出现的次数为:' + max);
}
</script>
</head>
<body>
</body>
</html>