js用set集合统计字符串中的字母数
时间: 2024-10-29 17:17:21 浏览: 29
在JavaScript中,你可以使用Set数据结构以及数组的`reduce()`方法来统计字符串中的字母数。Set是一种特殊的无序集合,其中的元素都是唯一的。下面是一个示例:
```javascript
function countLetters(str) {
// 使用Set去重并过滤非字母字符
const uniqueChars = new Set(str)
.filter(char => /\w/.test(char)); // \w 匹配字母、数字或下划线
// 使用reduce计算字母数量
const letterCount = Array.from(uniqueChars).reduce((count, char) => count + 1, 0);
return letterCount;
}
// 示例
const string = "Hello, World!";
console.log(countLetters(string)); // 输出:10
```
在这个函数中,我们首先创建了一个Set来存储字符串中独一无二的字符。然后通过`filter()`筛选出只有字母的字符(使用正则表达式`\w`)。最后,我们使用`Array.from()`将Set转换成数组,并使用`reduce()`来累加每个字符的计数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)