首页 > 解决方案 > 接受字符串并返回字数的函数

问题描述

创建一个接受字符串并返回字数的函数。字符串将是一个句子。

样本输出:

countWords("This is a test") ➞ 4

代码

function countWords(str) {

    let count = 0;
	  
    [...str].forEach(x => x.length > 0)
      
    count++

    return count

}

countWords("Hello World")

当我调用这个函数时,我得到undefined is not iterable. 我使用传播运算符错了吗?

此外,有没有办法在 forEach 或其他方式中以不那么冗长的方式获取计数?我相信增量需要在 forEach 内,但不确定放在哪里。

标签: javascriptstringforeachdestructuring

解决方案


您可以简单地用空格字符拆分字符串以创建一个数组并返回该数组的长度

function countWords(str) {
  let count = str.split(' ').length;
  return count;
}

console.log(countWords("This is a test"));


推荐阅读