首页 > 解决方案 > Javascript split() 字数统计问题

问题描述

我必须在每个单词旁边显示字数。

let str = "Hello there, how are you? Can you tell me how to get to the nearest Starbucks?"
    
function countingWords(){
  if (str.length === 0){
      return null;
  }
  str = str.toLocaleLowerCase();

  str.split(" ").forEach(word => {
    console.log(word, "=", str.split(word).length-1,)
  });
  return
}
countingWords()

我的输出:

hello = 1
there, = 1
how = 2
are = 2
you? = 1
can = 1
you = 2
tell = 1
me = 1
how = 2
to = 2
get = 1
to = 2
the = 2
nearest = 1
starbucks? = 1

其中大部分是正确的,但我仍然得到一些错误的答案,例如“are=2”和“the=2”。有谁知道为什么或如何解决?

标签: javascriptstringfunctionsplit

解决方案


您可以尝试使用过滤器方法来计算单词。我认为它更具可读性。谢谢你。

let str = "Hello there, how are you? Can you tell me how to get to the nearest Starbucks?"
    
function countingWords() {
  if (str.length === 0){
      return null;
  }
  str = str.toLocaleLowerCase();
  const arrayOfWord = str.split(" ");

  arrayOfWord.forEach(word => {
    console.log(word, "=", arrayOfWord.filter(wordToCheck => wordToCheck === word).length);
  });
  
  return null;
}

countingWords();


推荐阅读