使用javascript计算字符串中字符的频率 [英] counting frequency of characters in a string using javascript
本文介绍了使用javascript计算字符串中字符的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写某种循环来计算字符串中每个字母的频率。
I need to write some kind of loop that can count the frequency of each letter in a string.
例如:aabsssd
输出:a:2,b:1,s:3,d:1
output: a:2, b:1, s:3, d:1
还想将相同的字符映射为属性名称在对象中。有什么好主意怎么做?
Also want to map same character as property name in object. Any good idea how to do this?
我不知道怎么做。
这是哪里我到目前为止:
This is where I am so far:
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
function counter(x) {
var count=0, temp = [];
x = x.split('');
console.log(x);
for(var i=0, len = x.length; i < len; i++) {
if(x[i] == "a") {
count++;
}
}
return count;
}
var a = "aabbddd";
console.log(counter(a));
推荐答案
在这里:
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
这篇关于使用javascript计算字符串中字符的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文