我制作了JS代码,该代码跟踪每个骰子面的频率超过60000卷。我需要在网页上显示它,我似乎无法正确执行。
我尝试将Outputarea元素设置为一个称为REDID的变量,然后将REFID的Innertext设置为函数输出,但是将"未定义"输出到控制台中。
<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>
预期的输出是频率的列表,但是我一直在网页上获得一条"未定义"的行。
Console.log
未设置函数输出。用return
语句设置,否则未定义。改用此方法:
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>