javascript - 接受字符串并返回字数的函数
问题描述
创建一个接受字符串并返回字数的函数。字符串将是一个句子。
样本输出:
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 内,但不确定放在哪里。
解决方案
您可以简单地用空格字符拆分字符串以创建一个数组并返回该数组的长度:
function countWords(str) {
let count = str.split(' ').length;
return count;
}
console.log(countWords("This is a test"));
推荐阅读
- node.js - 在 Ubuntu Server 20.04LTS 上全局安装 PM2 时出错
- ios - 如何计算 UIViewController 的内在内容高度?
- prolog - 为什么 prolog 无法找到到顶点的路径(在图中)?
- user-interface - 外部监视器的 JavaFx 问题
- c++ - 解决正交模块的依赖关系
- python - 如何使用 Selenium 和 Python 相对于 xpath 中的变量定位元素
- amazon-web-services - AWS 如何将更改通知 API 用户?
- swiftui - 从图像 swiftUI 中获取 RGB 强度
- javascript - GrapeCity ActiveReportsJS 如何为数据源传递授权标头
- javascript - Angular 9:[innerHTML] 即使是纯字符串也无法在不清理值的情况下工作