I need help looping through the array using the results from the function I created.
The function rolls 2 dice and outputs the 2 dice numbers 1-6 and then indicates the sum of the roll I need HELP tracking the results after each roll.
Null is for zero and one that can not be the result of a 2 dice throw!
let results = [null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function rollDice(){
let dice0 = document.getElementById("dice0");
let dice1 = document.getElementById("dice1");
let result=document.getElementById("result");
let d0= Math.floor(Math.random()*6)+1;
let d1= Math.floor(Math.random()*6)+1;
let total = d0+d1;
dice0.innerHTML = d0;
dice1.innerHTML = d1;
result.innerHTML = "You rolled "+total+"."
Goal: display results 2-12 on the HTML page and how many times each number was rolled!
Example Expected results:
You have rolled 2; 4 times
You have rolled 3; 9 times
You have rolled 4; 7 times
...so on and so forth
Here is the HTML for those that want to see it:
<body>
<div id="dice0" class="dice">0</div>
<div id="dice1" class="dice">0</div>
<br>
<button onclick ="rollDice()">Roll a Pair of Dice</button>
<div id="result"></div>
<div id="list"></div>
<script src="code.js"></script>
</body>
</html>
let results = [null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function rollDice() {
let dice0 = document.getElementById("dice0");
let dice1 = document.getElementById("dice1");
let result = document.getElementById("result");
let d0 = Math.floor(Math.random() * 6) + 1;
let d1 = Math.floor(Math.random() * 6) + 1;
let total = d0 + d1;
dice0.innerHTML = d0;
dice1.innerHTML = d1;
result.innerHTML = "You rolled " + total + "."
}
<div id="dice0" class="dice">0</div>
<div id="dice1" class="dice">0</div>
<br>
<button onclick="rollDice()">Roll a Pair of Dice</button>
<div id="result"></div>
<div id="list"></div>
Please use this code.
let results = [null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function rollDice(){
let dice0 = document.getElementById("dice0");
let dice1 = document.getElementById("dice1");
let result = document.getElementById("result");
let list = document.getElementById("list");
let d0= Math.floor(Math.random()*6)+1;
let d1= Math.floor(Math.random()*6)+1;
let total = d0+d1;
dice0.innerHTML = d0;
dice1.innerHTML = d1;
result.innerHTML = "You rolled "+total+"."
results[total]++;
list.innerHTML = results.map((val, index) => `You have rolled ${index}; ${val} times`).join('<br/>');
}
When the user have clicked the button, the rolled times are saved in results variable. Then we get the list of each points from "results" variable with map method and show this in "list" div.