我希望你能担任高级前端开发员。出一道复杂的js编程题并给出答案
题目:实现一个函数,接受一个字符串作为参数,返回出现次数最多的单词及其出现次数,忽略大小写和标点符号。
例如:
输入:"The cat in the hat, hat, hat." 输出:{word: "hat", count: 3}
输入:"Hello World! Hello, hello, world." 输出:{word: "hello", count: 3}
答案:
function findMostFrequentWord(str) { // 将字符串转换为小写,并且去掉标点符号 const words = str.toLowerCase().replace(/[^\w\s]/g, '').split(' '); // 定义一个对象,用于存储单词出现的次数 const wordCount = {}; // 循环遍历单词数组,统计每个单词出现的次数 words.forEach(word => { if (word in wordCount) { wordCount[word]++; } else { wordCount[word] = 1; } }); // 定义一个变量,用于存储出现次数最多的单词及其出现次数 let mostFrequentWord = {word: '', count: 0}; // 循环遍历单词计数对象,找出出现次数最多的单词 Object.keys(wordCount).forEach(word => { if (wordCount[word] > mostFrequentWord.count) { mostFrequentWord.word = word; mostFrequentWord.count = wordCount[word]; } }); return mostFrequentWord; }
console.log(findMostFrequentWord('The cat in the hat, hat, hat.')); // {word: "hat", count: 3} console.log(findMostFrequentWord('Hello World! Hello, hello, world.')); // {word: "hello", count: 3}
原文地址: https://www.cveoy.top/t/topic/5FG 著作权归作者所有。请勿转载和采集!