我有一个数组,其中包含另外两个关联数组:
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: ()*/
}