我必须计算每个字母出现在字符串中的次数。
不区分大小写。
例如:
var str =“aaaAAAbbB”
会打印“A:6,B:3”
这就是我所拥有的,但它将小写和大写分开。
var string = document.getElementById("text").value
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++)
{
ch = string.charAt(index);
count = counts[ch];
counts[ch] = count ? count + 1 : 1;
}
for (ch in counts)
{
console.log(ch+" count: "+counts[ch]);
}
答案 0 :(得分:7)
ch = string.charAt(index).toUpperCase();
// ^^^^^^^^^^^^^^
var string = "aaaAAAbbB";
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++) {
ch = string.charAt(index).toUpperCase();
count = counts[ch];
counts[ch] = count ? count + 1 : 1;
}
for (ch in counts) {
console.log(ch + " count: " + counts[ch]);
}
比较风格
var string = "aaaAAAbbB",
counts = {};
string.split('').forEach(function (c) {
counts[c.toUpperCase()] = (counts[c.toUpperCase()] || 0) + 1;
});
console.log(counts);
答案 1 :(得分:0)
为了解决您的问题,我只想使用
string.toLowerCase();
然后你可以计算每个角色。
我修改了你的代码:
var string = document.getElementById("text").value.toLowerCase();
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++)
{
ch = string.charAt(index);
count = counts[ch];
counts[ch] = count ? count + 1 : 1;
}
for (ch in counts)
{
console.log(ch+" count: "+counts[ch]);
}
答案 2 :(得分:0)
您可以使用.toLowerCase()方法,将所有文本更改为小写 然后您的代码应如下所示:
var string = document.getElementById("text").value.toLowerCase()
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++)
{
ch = string.charAt(index);
count = counts[ch];
counts[ch] = count ? count + 1 : 1;
}
for (ch in counts)
{
console.log(ch+" count: "+counts[ch]);
}
答案 3 :(得分:0)
var str = "aaaAAAbbB";
var result = {};
//lowercase so they are all insensative and split to get an array. loop over the array
str.toLowerCase().split('').forEach(function(element, index, array){
//if not processed before, perform count
if (!result[element]) {
result[element] = array.filter(function(element2){ return element2 === element; }).length;
}
});
console.log(result);
&#13;