javascript - 如何在表格中显示关联数组?

标签 javascript arrays html-table associative-array coin-flipping

有人可以帮助我吗?我正在为“运气游戏”编写一个脚本,其目标是

  1. 接受用户输入的任何数字,生成一个从 0 到他们输入的数字的随机数,并将其显示在结果数组中。

  2. 模拟“正面或反面”游戏,并在同一结果数组中显示结果(我将使用关联数组)

  3. 运行上述两个目标总共 6 次。

  4. 在表格中显示结果。

  5. 合计“正面”的数量和“反面”的总数并显示它们。

  6. 返回 6 个结果中最小的数字。

我已经完成了第 1、2 和 3 项。我只需要第 6 项的帮助。如何在标题为“硬币面”和“数字”的 2x7 表格上显示我的结果以及如何求和找出 6 次试验的所有“正面”和“反面”,并返回生成的最小数字?

 <body>
 <div id = "luckGame"></div>

 var userInput = prompt("Enter maximum number output: ");
 printThis = document.getElementById('luckGame');

 function coinFlip() {
      return (Math.floor(Math.random() < 2) === 0) ? 'Heads' ; 'Tails';
 }

 for (var i = 0; i < 6; i++)
 {
      var result = [];

      result["randomNum"] = (Math.floor(Math.random()*userInput);

      result["coin"] = (coinFlip());

     printThis.innerHTML = result["coin"] + " " + result["randomNum"];
     //This loop will run 6 times.
     //This should print for example:  Heads  29 but I need to put all the results 
     //in a 2x7 table with labels "Coin Side" and "Number" included.  How do I do this?
 }

 //Code here needed to sum total of 'Heads' and 'Tails'
 //Code here needed to return the smallest number from the results.

 </body>

我的表格 CSS

 .results {
      border: 1px solid black;
      width: 200px;
      height: 20px;
   }

我的粗略表格

 var resultsTable = "<table class= 'results'><tr><td>" + "Coin Side" + "</td><td>" + "Number" + "</td></tr>";
     resultsTable += "<tr><td> + result["coin"] + "</td><td> + result["randomNum"] + </td></tr>";
     ... // repeat 4 more times.
     resultsTable += "<tr><td> + result["coin"] + "</td><td> + result["randomNum"] + </td></tr></table>;

如果我需要提供更多详细信息,请告诉我。

最佳答案

首先,创建一个带有标题的表格

var table = document.createElement("table");
table.innerHTML = "<tr><th>Coin Side</th><th>Number</th></tr>";

然后在循环中只需在末尾添加此代码即可向表中添加一行

var row = document.createElement("tr");
var coinCell = document.createElement("td");
var numCell = document.createElement("td");
coinCell.innerHTML = result["coin"];
numCell.innerHTML = result["randomNum"];
row.appendChild(coinCell);
row.appendChild(numCell);
table.appendChild(row);

最后,将表格添加到文档中

document.body.appendChild(table);

要计算正面和反面,请将此代码添加到现有循环中

(result["coin"] === "Heads") ? heads++ : tails++

只需创建两个全局变量并先将它们设置为零

var heads = 0;
var tails = 0;

要获取最小值,首先创建一个设置为最大值的全局变量

var min = eval(userInput);

然后,在循环中检查生成的数字是否小于当前的min

if(result["randomNum"] < min)
  min = result["randomNum"];

演示:https://codecanister.com/Project/d547eed9/5/result/

关于javascript - 如何在表格中显示关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38297051/

相关文章:

javascript - GSheet 的 Google 应用脚本 - 在 B 列上查找今天的日期,并在同一行的 C 列上写入当前时间

php - 从数组 : for loop not working 返回字母

C结构共享公共(public)指针?

php - 信息未插入表中

css - IE11 的 HTML 转换问题

javascript - 当单元格相同时制作行跨度

javascript - Cordova/Phonegap - beforeunload 工作或任何替代方案吗?

javascript - 通过链接 AJAX Promise 实现流畅的界面?

javascript - 如何结合 Angular 两个可观察结果?

arrays - 将数组的结果写入下一个可用单元格