计算每个循环中字符的出现次数

时间:2016-03-10 18:21:29

标签: javascript

我需要计算每个循环中所有字符的出现次数,基数为inputs

Object {SchriftEins: "abc ", SchriftZwei: "123"}

我有这段代码:

//go through every input
$.each(inputs,function(i,el){   
    var schrift = i;
    var string = el;

    // splitt string
    var string_as_array = string.split(""); 

    //count the occurrence of every char        
    $.each(string_as_array,function(i, el){
        // here is the problem:         
        arr[schrift][el] = arr[schrift][el] + 1 || 1;
    });         
    console.log(arr);   
}); 

我的问题是,计算错误。我假设因为嵌套的每个循环。如何修改此代码以获得正确的结果?

1 个答案:

答案 0 :(得分:3)

您可以使用内置迭代并循环遍历字符串,而不是拆分字符串并使用jQuery。它更简单,应该更多更快。

结合每个单词的字符数:

var characterCount = {};
Object.keys(inputs).forEach(function (item) {
  var value = inputs[item];
  for (var i = 0; i < value.length; ++i) {
    var char = value[i];
    characterCount[char] = (characterCount[char] || 0) + 1;
  }
});

或者,单独(如您的示例所示):

var characterCount = {};
Object.keys(inputs).forEach(function (item) {
  var value = inputs[item];
  for (var i = 0; i < value.length; ++i) {
    var char = value[i];

    // This will get existing counts, increment the proper field, and replace.
    // It is a somewhat naive solution and could be improved.
    var counts = characterCount[item] || {};
    counts[char] = (counts[char] || 0) + 1;
    characterCount[item] = counts;
  }
});