Skip to content
On this page

计算文章中数量最多的单词

核心代码

js
const findMostWord = (article) => {
    let max = 0;
    let maxWord = '';
    let wordCount = {};
    let words = article.split(' ');
    words.forEach(word => {
        if (wordCount[word]) {
            wordCount[word]++;
        } else {
            wordCount[word] = 1;
        }
        if (wordCount[word] > max) {
            max = wordCount[word];
            maxWord = word;
        }
    });
    return maxWord;
}

使用正则

js
function findMostWord(article) {
  // 合法性判断
  if (!article) return;
  // 参数处理
  article = article.trim().toLowerCase();
  let wordList = article.match(/[a-z]+/g),
    visited = [],
    maxNum = 0,
    maxWord = "";
  article = " " + wordList.join("  ") + " ";
  // 遍历判断单词出现次数
  wordList.forEach(function(item) {
    if (visited.indexOf(item) < 0) {
      // 加入 visited 
      visited.push(item);
      let word = new RegExp(" " + item + " ", "g"),
        num = article.match(word).length;
      if (num > maxNum) {
        maxNum = num;
        maxWord = item;
      }
    }
  });
  return maxWord + "  " + maxNum;
}

MIT Licensed | Copyright © 2021 - 2022