2

我有以下 JavaScript 数组:

var President = new Array();
President[0]="Thomas Jefferson";
President[1]="Thomas Jefferson";
President[2]="Thomas Jefferson";
President[3]="Thomas Jefferson";
President[4]="Thomas Jefferson";
President[5]="Thomas Jefferson";
President[6]="Thomas Jefferson";
President[7]="Thomas Jefferson";
President[8]="Thomas Jefferson";
President[9]="Thomas Jefferson";
President[10]="Thomas Jefferson";
President[11]="Thomas Jefferson";
President[12]="Thomas Jefferson";
President[13]="James Madison";
President[14]="James Madison";
President[15]="James Madison";
President[16]="James Madison";
President[17]="James Madison";
President[18]="James Madison";
President[19]="James Madison";
President[20]="Abraham Lincoln";
President[21]="Abraham Lincoln";
President[22]="Abraham Lincoln";
President[23]="Abraham Lincoln";
President[24]="Abraham Lincoln";
President[25]="George Washington";

如何统计重复的项目,以便输出如下:

Thomas Jefferson: 13
James Madison: 7
Abraham Lincoln: 5
George Washington: 1

谢谢你的帮助!

4

2 回答 2

2

@Tyson:不应该使用 for.. in 遍历数组。

  for (var stats = {}, potus, i = President.length; i--;) {
    if (!((potus = President[i]) in stats)
      stats[potus] = 0; // Initialize a new counter
    stats[potus]++;
  }

  // Now stats['Thomas Jefferson'] will be 13 etc.
于 2012-06-05T17:07:11.920 回答
0

我不是 javascript 开发人员,但根据这篇关于 js 中的哈希表的文章,您似乎需要以下内容:

var h = new Object();
for (var p in President) {
    if (h.hasItem(p)) {
        h.setItem(p, h.getItem(p) + 1);
    }
    else {
        h.setItem(p, 1);
    }
}

for (var p in h)
{
    document.write(p);
    document.write(":");
    document.write(h.getItem(p));
    document.write("<br />");
}
于 2012-06-05T15:58:51.697 回答