首页 > 其他分享 >js统计字符串每个字符出现的次数

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

时间:2022-10-21 22:49:13浏览次数:45  
标签:字符 ... ++ js let result str 字符串

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

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);

标签:字符,...,++,js,let,result,str,字符串
From: https://www.cnblogs.com/bingquan1/p/16814992.html

相关文章