方法一:普通方法
// 设置一个字符串
let str = 'dhadaiiamnfhuhuahahhd'
// 设置一个对象,储存每个字符的个数
let result = {}
// 向result储存每个字符的个数
for(let i = 0; i < str.length ; i++) {
// 如果已经存在这个字符,则字符个数+1,若是不存在,则字符串个数等于1
if(result[str[i]]) {
result[str[i]]++
}else {
result[str[i]] = 1
}
}
// 储存个数最多的字符
var maxStr = ''
// 最多字符的个数
let maxIndex = 0
for(let i in result) {
if(result[i] > maxIndex) {
maxIndex = result[i]
maxStr = i
}
}
console.log(`个数最多的字符是${maxStr}, 个数为${maxIndex}`)代码片
方法二:reduce方法
let str = 'dhadaiiamnfhuhuaahahhd'
// 将字符串转化为数组
let arr = str.split('')
// 向result储存每个字符的个数
let result = arr.reduce((pre, cur) => {
cur in pre ? pre[cur] += 1 : pre[cur] = 1
return pre
}, {})
console.log(result);
// 储存个数最多的字符
var maxStr = ''
// 最多字符的个数
let maxIndex = 0
for(let i in result) {
if(result[i] > maxIndex) {
maxIndex = result[i]
maxStr = i
}
}
console.log(`个数最多的字符是${maxStr}, 个数为${maxIndex}`)
更多关于前端知识请访问我的知识花园