gpt4 book ai didi

javascript - 统计数组中的重复项

转载 作者:行者123 更新时间:2023-11-29 22:23:33 25 4
gpt4 key购买 nike

我有以下 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

感谢您的帮助!

最佳答案

@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.

关于javascript - 统计数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com