I made js code that tracks the frequency of each dice face over 60000 rolls. I need to display it on a web page, which I can't seem to properly do.
I tried setting the outputArea element to a variable called refID, then setting the innerText of refID to the function output, but that outputs an 'undefined' into the console.
<div id="outputArea"></div>
<script type="text/javascript">
//declaring workspace variables
function output()
{
let iteration, dice, n;
//initializing variables
iteration = 0;
dice = [0,0,0,0,0,0,0];
//iterating through 60000 values and logging each item to its corresponding face value
while (iteration < 60000) {
// asign n to a random integer between 1 and 6
n = Math.floor((Math.random() * 6) + 1);
//increment 1 to each value of n
dice[n] += 1;
iteration = iteration + 1;
}
//display each element from dice
for (var i = 1; i < dice.length; i++) {
console.log(i+ ":" + dice[i]);
}
}
var refID = document.getElementById("outputArea")
refID.innerHTML = output()
</script>
The expected output is a list of frequencies, but I keep getting a single line that says 'undefined' on the webpage instead.
Console.log
doesn't set a function output. That is set with a return
statement or else is undefined. Try this instead:
function output() {
let returnVal, outputString, iteration, dice, n;
//initializing variables
iteration = 0;
dice = [0, 0, 0, 0, 0, 0, 0];
//iterating through 60000 values and logging each item to its corresponding face value
while (iteration < 60000) {
// asign n to a random integer between 1 and 6
n = Math.floor((Math.random() * 6) + 1);
//increment 1 to each value of n
dice[n] += 1;
iteration = iteration + 1;
}
//display each element from dice
for (var i = 1; i < dice.length; i++) {
outputString = i + ":" + dice[i];
console.log(outputString);
if (!returnVal) {
returnVal = outputString;
} else {
returnVal = returnVal + "\n" + outputString;
}
}
return returnVal;
}
var refID = document.getElementById("outputArea")
refID.innerHTML = output()
<body>
<div id="outputArea" style="white-space:pre-wrap"></div>
</body>
The very first output is still undefined, but the rest is displayed
Yeah, I just updated the code to fix that. Have to check for the first cycle.
And also if you do it like this you will need to make sure your output is a
pre
element or else has the stylewhite-space: pre-wrap
like in my example. This is so the linebreaks are preserved in the output.