js统计字符串每个字符出现的次数

js统计字符串每个字符出现的次数

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>统计次数</title>
  </head>
  <body>
    <h1>const str = 'abc;uag;yafu;bda' 统计字符串每个字符出现的次数</h1>
  </body>
  <script>
    const str = "abc;uag;yafu;bda";

    // 方案一:使用reduce
    const charCount = str.split("").reduce((pre, cur) => {
      // in 用来判断一个属性是否属于一个对象,即判断字符串是否在keys中
      if (cur in pre) {
        pre[cur]++;
      } else {
        pre[cur] = 1;
      }
      return pre;
    }, {}); // 第二个参数{}必须传
    console.log(JSON.stringify(charCount)); // {"a":4,"b":2,"c":1,";":3,"u":2,"g":1,"y":1,"f":1,"d":1}

    //方案二:for循环
    let charCount2 = {};
    const arr = str.split("");
    for (let i = 0; i < arr.length; i++) {
      const key = arr[i];
      if (charCount2[key]) {
        charCount2[key]++;
      } else {
        //把字母加到对象中
        charCount2[key] = 1;
      }
    }
    console.log(JSON.stringify(charCount2)); //{"a":4,"b":2,"c":1,";":3,"u":2,"g":1,"y":1,"f":1,"d":1}
  </script>
</html>
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值