gpt4 book ai didi

javascript - 字符串中每个字符的出现

转载 作者:行者123 更新时间:2023-11-28 12:38:16 24 4
gpt4 key购买 nike

如何编写 JavaScript 代码来计算字符串中每个字符的出现次数?

e.g 
String is : Hello World

Output :
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1

最佳答案

var counts = {};
yourstring.split('').map(function(ch) {
counts[ch] = (counts[ch] || 0) + 1;
});

或者时髦地使用map/reduce:

var counts = yourstring.split('').reduce(function(dst, c) {
dst[c] = (dst[c] || 0) + 1;
return dst;
}, {});

关于javascript - 字符串中每个字符的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14798049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com