2

通过正则表达式和 Greasemonkey,我得到了一系列结果,如下所示:
choice1, choice2, choice3, choice3, choice1, etc..

我的问题是我如何计算选择,以便我知道选择 1 在数组中的次数,选择 2 在数组中的次数,等等。如果我不确切知道有多少选择或它们是什么。

最终目标是创建一个 Greasemonkey 脚本,该脚本存储每个选择在多个页面上获得的票数(可能使用 gm_setvalue,尽管我对其他想法持开放态度。)

谢谢!

4

3 回答 3

2

一种技术是迭代选择并增加与对象属性中每个唯一选择相关联的计数器。

例子:

var choiceCounts = {};
for (var iLoop=0; iLoop < aChoices.length; iLoop++) {
  var keyChoice = aChoices[iLoop];
  if (!choiceCounts[keyChoice]) {
    choiceCounts[keyChoice] = 1;
  } else {
    choiceCounts[keyChoice]++;
  } //if
} //for

然后,您有一个对象,其属性等于该属性在数组中存在的次数。

于 2008-12-07T20:38:37.303 回答
1

不是 100% 确定您在寻找什么,但我认为就是这样。

  // Original data
    var choices = [
        "choice 1",
        "choice 1",
        "choice 2",
        "choice 3",
        "choice 3",
        "choice 3",
        "choice 3",
        "choice 3",
        "choice 3",
        "choice 4",
        "choice 4",
        "choice 4"];


    //Create the results array
    var result = new Object();

    for (var choice in choices) {
        if (result[choices[choice]] === undefined)
            result[choices[choice]] = 1;
        else
            result[choices[choice]]++;
    }

    //Print result
    var str = "";

    for (var item in result)
        str += item + ": " + result[item] + "<br />";


    document.getElementById("resultDiv").innerHTML = str;

输出:

choice 1: 2
choice 2: 1
choice 3: 6
choice 4: 3
于 2008-12-07T20:33:50.463 回答
0

首先对数组进行排序,然后您可以进行一次扫描以计算出现次数(类似于上面 Ryan 的建议)。

于 2008-12-07T21:21:37.683 回答