JavaScript:如何计算关联数组中随机硬币翻转的头部和尾部总数?

时间:2016-07-04 05:56:36

标签: javascript loops associative-array coin-flipping

我有一个数组,其中有两个其他关联数组:

 var coinToss = [];

 coinToss["FlipNumber"]; coinToss["Result"];

我已经有了随机函数功能和一切。我只需要帮助总计所有'头'和'尾'的总和。

我尝试过:

 for (var i = 0; i < coinToss.length; i++)
 {
      var headCount = 0, tailCount = 0;

      if (coinToss["Result"] === 'heads')
            headCount++;
      else
            tailCount++;
 }
 document.getElementByID.innerHTML += "Heads: " + headCount + " " + "Tails: " + tailCount + "<br>";

但它只打印出每个单独的结果,例如5个硬币翻转:

 //*Heads: 1   Tails: 0 *
 //*Heads: 1   Tails: 0 *
 //*Heads: 0   Tails: 1 *
 //*Heads: 1   Tails: 0 *
 //*Heads: 0   Tails: 0 *

我想要的是将所有'头'加起来并分别加上所有'尾巴'。为什么每次循环重复时它会重置为0?

按要求编辑:

 function coinFlip() {
        return (Math.floor(Math.random() * 2) === 0) ? 'heads' : 'tails';
 }

 for (var x = 0; x < 6 (/*i.e. number of coin toss*/); x++)
 {
     var coinToss = [];
     coinToss["flipNumber"] = /*varies by user input*/;
     coinToss["Result"] = (coinFlip());

     /*a print code that prints Flip Number: () and Result: ()*/
 }

2 个答案:

答案 0 :(得分:0)

这应该让你开始:

&#13;
&#13;
// Make sure you're declaring your variables outside of the for loop:

// I'm not sure what your actual array looks like, but let's say it looks something like this:
var arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];
arr["Result"] = "heads";
var headCount = 0, tailCount = 0;

for (var i = 0; i < arr.length; i++) {
    if (arr["Result"] === "heads")
        headCount += arr[i];
    else
        tailCount += arr[i];
}
console.log("Heads: " + headCount + " " + "Tails: " + tailCount);
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

//* these variables should be initialised outside the loop
//* otherwise they'll get initialised with zero each time the loop runs

var headCount = 0, tailCount = 0;

for (var i = 0; i < coinToss.length; i++) {

  if (coinToss["Result"] === 'heads')
        headCount++;
  else
        tailCount++;
 }

document.getElementByID.innerHTML += "Heads: " + headCount + " " +     "Tails: " + tailCount + "<br>";