如何用for循环遍历字符串字符并统计各字符出现次数存入对象?
如何遍历字符串统计字符出现次数并存入对象?
我在Codewars遇到这个问题,找了一圈没找到对应结构的解决方案,这里分享我的方法,希望能帮到大家。
示例
- 输入:
"Apple" - 输出:
{A: 1, p: 2, l: 1, e: 1}
解决方案思路与代码
核心逻辑是通过遍历字符串的每个字符,用对象动态记录每个字符的出现次数:
- 初始化空对象存储统计结果
- 遍历字符串的每一个字符
- 检查当前字符是否已在对象中:
- 存在则对应计数加1
- 不存在则以该字符为键,初始计数设为1
写法一(for...of循环)
function countChars(str) { const charCount = {}; for (let char of str) { // 保留原字符大小写,与示例规则一致 charCount[char] = (charCount[char] || 0) + 1; } return charCount; } // 测试示例 console.log(countChars("Apple")); // 输出 {A: 1, p: 2, l: 1, e: 1}
写法二(传统for循环)
function countChars(str) { const charCount = {}; for (let i = 0; i < str.length; i++) { const char = str[i]; charCount[char] = charCount[char] ? charCount[char] + 1 : 1; } return charCount; }
内容的提问来源于stack exchange,提问作者Ubeydullah Keleş
相关产品推荐
相关产品推荐

