如何计算每个单词出现在字符串中的次数?

时间:2017-03-10 03:53:14

标签: javascript

我现在正在学习JavaScript,而且我正在研究一个函数,该函数将计算字符串中出现的字数,然后将答案作为对象吐出。根据这个网站上类似线程的一些建议,我决定使用.split和一个计数器函数来制作一个二维数组,然后使用结果填充一个对象。当我遇到某些字符串的麻烦时,我正在运行带有示例文本的测试。我无法弄清楚为什么有些计数器显示为未定义。

function countWords(str) {
  var answer = {};
  if (str === '') {
    return answer;
  }
  var strArray = [];
  strArray = str.split(' ');
  //strArray is an array that holds the words as separate strings
  console.log('strArray: ' + strArray);
  var resultWords = [];
  var resultCount = [];
  var counter = 0;

  // only if the word doesnt show up in resultWords, push it in, and increase the counter. if it has shown up, disregard
  for (var i = 0; i<strArray.length; i++) {
    counter = 0;
    if (resultWords.indexOf( strArray[i] ) === -1)  {
      resultWords.push(strArray[i]);
      counter += 1;
      // if the word shows up again, increase the counter
      for (var j = i + 1; j < strArray.length; j++) {
        if (resultWords[i] === strArray[j]) {
          counter += 1;
        }
        // push to resultCount the counter for each word
        resultCount[i] = counter;
      }
    }
    // create an object where the key is the word from resultWords and the value is the number from wordCount
    for (var k = 0; k < resultWords.length; k++) {
      answer[ resultWords[k] ] = resultCount[k];            
    }
  }
  console.log('resultWords: ' + resultWords);
  console.log('resultCount: ' + resultCount);
  return answer;
}

var sample = 'how now brown cow how now';
console.log(sample);
var output = countWords( sample ); 

我发现当我使用&#34;这个&#34;和&#34;是&#34;在我的样本中,我经常回归&#34; undefined&#34;正如这些词的字数。例如,&#34;是或不是&#34;返回&#34; undefined&#34;因为&#34;那&#34;和&#34;是。&#34;有人可以帮助阐明这里发生了什么吗?谢谢。

1 个答案:

答案 0 :(得分:1)

您的代码无法阅读:

  • 代码块太长
  • 非信息性变量名称(例如answer

接下来,您的算法非常慢:您可以通过仅解析整个数组一次来计算单词。

最后但同样重要的是,您应该在循环外创建answer数组。

这是一个使用现代JavaScript功能的简短实现(为了学习):

function countWords(str) {
  const wordCounts = new Map()
  str.split(' ').forEach(word => {
    const currentWordCount = wordCounts.get(word) || 0
    wordCounts.set(word, currentWordCount+1)
  })

  /* Reproduce your output */
  const resultWords = [...wordCounts.keys()]
  const resultCount = [...wordCounts.values()]
  console.log('resultWords: ' + resultWords);
  console.log('resultCount: ' + resultCount);

  return wordCounts
}

在较旧的js环境中,您无法使用Map和箭头功能:

function countWords(str) {
  const wordCounts = {}
  str.split(' ').forEach(function(word) {
    const currentWordCount = wordCounts[word] || 0
    wordCounts[word] = currentWordCount+1
  })

  /* Reproduce your output */
  const resultWords = Object.keys(wordCounts)
  const resultCount = resultWords.map(function(word) { return wordCounts[word] })
  console.log('resultWords: ' + resultWords);
  console.log('resultCount: ' + resultCount);

  return wordCounts
}

回到你的代码,你得到一些undefined因为这一行:

// push to resultCount the counter for each word
resultCount[i] = counter;

索引istrArray中当前单词的索引。您可以通过删除此行来修复它,然后执行

resultCount.push(counter)

for (var j = i + 1; j < strArray.length; j++)开头的循环结束。