使用数组循环计算出现次数

时间:2015-10-22 07:25:55

标签: javascript

['a','a','b','a','s','g','h','t']

我有上面的数组,使用循环,如何知道所有字母的出现次数?例如a出现了多少次?

预期结果如下:

a - 3
b - 5
s - ..

依旧......

4 个答案:

答案 0 :(得分:1)

这是一种方法:

// Declare an array, in which you will store the distinct elements
// of your initial array.
var characters = [];

// Declare an array, in which you will store the times you find 
// each distinct element in your initial array.
// The counter in the 1st position is associated with the character 
// in the 1st position of characters.
var counters = [];

// Your initial array.
array = ['a','a','b','a','s','g','h','t'];

// Loop through the items of your array
for(var i=0, len=array.length; i<len; i++){

    var indexOfChar = characters.indexOf(array[i]);

    // If the current item is not included in the characters
    // push it there and push the corresponding counter to the
    // counters.
    if(indexOfChar===-1){
        characters.push(array[i]);
        counters.push(1);
    }else{ // The current item is found. So just increment the counter.
        counters[indexOfChar] += 1;
    }
}

// Print the results
for(var i=0, len=characters.length; i<len; i++){
    document.write(characters[i]+'-'+counters[i]+'<br/>');
}

&#13;
&#13;
var characters = [];
var counters = [];
array = ['a','a','b','a','s','g','h','t'];

for(var i=0, len=array.length; i<len; i++){
    var indexOfChar = characters.indexOf(array[i]);
    if(indexOfChar===-1){
        characters.push(array[i]);
        counters.push(1);
    }else{ 
        counters[indexOfChar] += 1;
    }
}

for(var i=0, len=characters.length; i<len; i++){
   document.write(characters[i]+'-'+counters[i]+'<br/>');
}
&#13;
&#13;
&#13;

  

这可以在forEach中完成吗?这伤害了我的眼睛

当然可以,但这不是我的第一个念头:(

&#13;
&#13;
var array = ['a','a','b','a','s','g','h','t'];
var dict = {}; 
array.forEach(function (char) { dict[char] = dict[char] ? dict[char] + 1 : 1; }); 
for(var key in dict){
    if(dict.hasOwnProperty(key)){
        document.write(key+'-'+dict[key]+'<br/>');
    }
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var myarray = ['a','a','b','a','s','g','h','t'];
var countarray = [];

var Item = function(letter){
  this.letter = letter;
  this.count = 0;
}
for(var i=0;i<myarray.length;++i){
  countarray[myarray[i]] = countarray[myarray[i]] || new Item(myarray[i]);
  countarray[myarray].count++;
}

答案 2 :(得分:0)

您可以创建包含特定数组元素数的新对象。

请参考以下示例创建一个具有关于每个角色的出现的所有细节的对象 -

set /p in=Guess it.

要检查示例,请使用此链接 - http://jsfiddle.net/ks9tt953/

答案 3 :(得分:-1)

试试这段代码:

   var freq = [];
   var ar = ['a', 'a', 'b', 'a', 's', 'g', 'h', 't'];
    for (x = 0; x < ar.length; x++) {
        freq[ar[x]] = 0;
    }/*Initialize*/

    for (y = 0; y < ar.length; y++) {
        freq[ar[y]] += 1;
    }/*Operate*/

    for (i in freq) {
        console.log(i + "-" + freq[i]);
        /*This will display your desired output*/
    }/*Output*/

我希望它有所帮助。