计算字符在字符串中出现的次数并将其存储在数组JavaScript中

时间:2016-01-29 21:46:10

标签: javascript arrays string count character

我一直试图弄清楚如何计算一个字符在字符串中出现的次数,并将其存储在另一个变量中,该变量将保存字符及其在字符串中出现的次数。

例如:

var greeting = "Hello World";

[H]发生[1]时间。

[e]发生[1]时间。

[l]发生[3]次。

[o]发生[2]次。

[W]发生[1]时间。

[r]发生[1]时间。

[d]发生[1]时间。

我是一名JS初学者,我尽可能多地遵循指南和教程,但这个练习似乎超出了我的联盟。关于你们如何继续解决这个问题,我将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

你基本上想要在字符串中创建一组映射的字符。将这些东西存储在一个数组中可能很奇怪,因为你需要2个Dimentional数组。而是将其存储在哈希对象中。

var greeting = "Hello world!";

var hash = {};
for(var i = 0; i < greeting.length; i++){
  if(hash[greeting[i]] === undefined){
    hash[greeting[i]] = 1;
  } else {
    hash[greeting[i]] += 1;
  }
}

// printing the stuff in hash.
for(var x in hash){
  if(hash.hasOwnProperty(x)){
    console.log(x, hash[x]);
  }
}

无论如何,如果你需要这些东西在数组中,你可以这样说:

var arr = [];
var i = 0;
for(var x in hash){
  if(hash.hasOwnProperty(x)){
    arr[i++] = [x, hash[x]];
  }
}

for(var i = 0; i< arr.length; i++){
  console.log(arr[i]);
}

但我不推荐它。你可以看到自己的冗余。

答案 1 :(得分:0)

试试这个:

var result = {};

Array.prototype.map.call('Hello world!', function(x) {
  if (typeof result[x] == 'undefined') {
    result[x] = 1;
  } else {
    result[x] += 1;    
  }
});
console.log(result);

&#13;
&#13;
var result = {};

Array.prototype.map.call('Hello world!', function(x) {
  if (typeof result[x] == 'undefined') {
    result[x] = 1;
  } else {
    result[x] += 1;    
  }
});
console.log(result);
&#13;
&#13;
&#13;