我制作了js代码,用于跟踪超过60000卷骰子的频率。我需要将其显示在网页上,但似乎无法正确显示。
我尝试将outputArea元素设置为一个名为refID的变量,然后将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>
第一个输出仍未定义,但其余显示
是的,我刚刚更新了代码以解决此问题。必须检查第一个周期。
而且,如果您这样做,则需要确保您的输出是一个
pre
元素,或者具有与white-space: pre-wrap
我的示例类似的样式。这样可以将换行符保留在输出中。