代码之家  ›  专栏  ›  技术社区  ›  Sean

数组中的计数结果

  •  2
  • Sean  · 技术社区  · 17 年前

    通过正则表达式和Greasemonkey,我得到了如下结果数组:
    choice1, choice2, choice3, choice3, choice1, etc..

    我的问题是,如果我不知道到底有多少个选项或它们是什么,我该如何统计这些选项,以便知道choice1在数组中的次数,choice2在数组中的次数,等等。

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

    谢谢

    3 回复  |  直到 17 年前
        1
  •  2
  •   J c    17 年前

    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
    

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

        2
  •  1
  •   Ryan Cook    17 年前

    不是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
    
        3
  •  0
  •   joel.neely    17 年前