欢迎来到码农权的博客 MaNongGeGe.|

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

统计下面字符串中每个字符出现的频率

let str = "fgasdfadfdasd"
let result = {}

for (let i = 0; i < [...str].length; i++) {
  if (!result[[...str][i]]) {
    result[[...str][i]] = 1
  } else {
    result[[...str][i]]++
  }
}
console.log("方法一:", result)

let res = [...str].reduce((a, b) => {
  a[b] ? a[b]++ : a[b] = 1
  return a
}, {})
console.log("方法二:", res);

// 最简化
let res = [...str].reduce((a, b) => (a[b]++ || (a[b] = 1), a), {})
console.log("方法二:", res);

本文作者:HuangBingQuan

本文链接:https://www.cnblogs.com/bingquan1/p/16814992.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   HuangBingQuan  阅读(502)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 不将就 码农权
  2. 2 Bleeding Love 码农权
  3. 3 想你念你 码农权
Bleeding Love - 码农权
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available