统计字符串中出现次数最多的字符

博客介绍了前端算法的两种实现方法,分别是普通方法和 reduce 方法,为前端开发提供了不同的算法实现思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:普通方法

// 设置一个字符串
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}`)

更多关于前端知识请访问我的知识花园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值