方法一: 使用reduce()方法
先用 split() 方法将字符串分割成数组,再使用 reduce() 方法判断每一个字是否存在过,存在就累加,不存在就新增。
const str = '季姬寂,集鸡,鸡即棘鸡。棘鸡饥叽,季姬及箕稷济鸡。'
const count = str.split('').reduce((prev,item)=>{
if ( prev[item] ) {
prev[item]++
} else {
prev[item] = 1
}
return prev
}, {})
console.log( count )
控制台输出结果为
方法二: 使用 forEach()方法
核心思想都是循环遍历再判断
const str = '石室诗士施氏,嗜狮,誓食十狮。施氏时时适市视狮。十时,适十狮适市。是时,适施氏适市。'
const count = {}
str.split('').forEach((res => {
if ( count[res] ) {
count[res]++
} else {
count[res] = 1
}
}))
console.log(count)
控制台输出结果为