You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环遍历字符串字符并统计各字符出现次数存入对象?

如何遍历字符串统计字符出现次数并存入对象?

我在Codewars遇到这个问题,找了一圈没找到对应结构的解决方案,这里分享我的方法,希望能帮到大家。

示例

  • 输入:"Apple"
  • 输出:{A: 1, p: 2, l: 1, e: 1}

解决方案思路与代码

核心逻辑是通过遍历字符串的每个字符,用对象动态记录每个字符的出现次数:

  1. 初始化空对象存储统计结果
  2. 遍历字符串的每一个字符
  3. 检查当前字符是否已在对象中:
    • 存在则对应计数加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ş

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 07:42:02