-1

我有一个数组,其中包含另外两个关联数组:

 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: ()*/
 }
4

2 回答 2

0

这应该让你开始:

// 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);

于 2016-07-04T05:57:58.767 回答
-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>";
于 2016-07-04T06:08:39.723 回答