使用 reduce 计算词频

132 阅读1分钟

使用原生方法计算词频🌳

const str = 'Whatever is worth doing is worth doing well'
const count = str.replace(/\s*/g,"").split('').reduce((obj, ele) => {
  obj[ele] = (obj[ele] || 0) + 1
  return obj
},{})

1. 使用正则表达式替换所有空格

2. 使用 reduce 方法,首先初始一个对象

3. 对每个字母进行 key-value 匹配

4. 返回计算对象