使用JavaScript给出字符串中产生的字符数的计数

时间:2018-09-21 16:31:43

标签: javascript arrays string

这是我编写的要计数的代码

var name = "Interesting";
var letter_count = {};
 for(var i in name){
   if (!(i in letter_count)){
    letter_count[i] = 1;
   }
  else {
   letter_count[i] += 1;
  }
}
console.log(letter_count);

预期输出:   { i: 2, n:2, t:2, e:2, r:1 s:1, g:1 }

4 个答案:

答案 0 :(得分:4)

for...in中的变量i表示键(或数组的索引)。由于不需要索引,请改用for...of

var name = "Interesting";
name = name.replace(/ +/g, "").toLowerCase();
// name = name.split('').join(''); // remove - this doesn't do anything
var letter_count = {}

for(var i of name){
   if (!(i in letter_count)){
    letter_count[i] = 1;
   }
  else {
   letter_count[i] += 1;
  }
}

console.log(letter_count);

答案 1 :(得分:2)

如果您需要精美的功能编程方法:

const letterCount = name.toLowerCase().split('').reduce((acc, curr) => {
    acc[curr] ? acc[curr]++ : acc[curr] = 1;
    return acc;
}, {});

console.log(letterCount);

您可以在以下位置找到reduce函数的文档:link

答案 2 :(得分:1)

我认为您对如何使用i变量感到有些困惑。它实际上是字符的索引,而不是字符。要获取角色,您需要使用var c = name[i];

var name = "Interesting";
name = name.replace(/ +/g, "").toLowerCase();
name = name.split('').join('');
var letter_count = {}

for(var i in name){
   var c = name[i];
   if (!(c in letter_count)){
    letter_count[c] = 1;
   }
  else {
   letter_count[c] += 1;
  }
}

console.log(letter_count);

答案 3 :(得分:1)

您的代码中有一些不必要和错误的内容,我将它们放在代码中的注释中

var name = "Interesting";
// you do not need to do this name = name.replace(/ +/g, "").toLowerCase();
name = name.toLowerCase();
// nor this name = name.split('').join('');
var letter_count = {}

for(var i in name){
   var character = name[i]; // here we set the value of character to be letter from name
   if (!(character in letter_count)){
    letter_count[character] = 1; // here we are giving it initial value if it is not found so far
   }
  else {
   letter_count[character] += 1; // here we are giving it value if it already exists
  }
}

console.log(letter_count);