我正在练习使用while循环进行赋值,并尝试使用Math.random生成一个包含10次迭代的循环,因此每次都会得到一个随机数。相反,我连续10次列出相同的数字。不知道我在这里做错了什么?在HTML中使用以一次显示所有结果。
<script type="text/javascript">
var x = 0;
function showResults() {
var randomNum = Math.floor(Math.random() * 999) + 1;
loopOutput = "";
while (x < 10) {
x++;
document.getElementById("loopResults").innerHTML += "<p>Our answer: " + x + ". " + randomNum + "</p>";
}} //end function showResults()
</script>
答案 0 :(得分:0)
只需将随机数的计算移动到循环中:
var x = 0;
function showResults() {
loopOutput = "";
while (x < 10) {
var randomNum = Math.floor(Math.random() * 999) + 1;
document.getElementById("loopResults").innerHTML += "<p>Our answer: " + x + ". " + randomNum + "</p>";
x++;
}} //end function showResults()
答案 1 :(得分:0)
<script type="text/javascript">
var x = 0;
function showResults() {
loopOutput = "";
while (x < 10) {
var randomNum = Math.floor(Math.random() * 999) + 1;
x++;
document.getElementById("loopResults").innerHTML += "<p>Our answer: " + x + ". " + randomNum + "</p>";
}} //end function showResults()
</script>
答案 2 :(得分:0)
随机数仅在调用函数时生成一次,但您需要生成数字10次,因此您将
var randomNum = Math.floor(Math.random() * 999) + 1;
在while循环中,最后它将如下所示:
<script type="text/javascript">
var x = 0;
function showResults() {
loopOutput = "";
while (x < 10) {
var randomNum = Math.floor(Math.random() * 999) + 1;
x++;
document.getElementById("loopResults").innerHTML += "<p>Our answer: " + x + ". " + randomNum + "</p>";
}} //end function showResults()
答案 3 :(得分:0)
loopOutput
进行HTML字符串连接相反:
function showResults() {
var x = 0,
loopOutput = "";
while (x < 10) {
x++;
var randomNum = Math.floor(Math.random() * 999) + 1;
loopOutput += "<p>Our answer: " + x + ". " + randomNum + "</p>";
}
// Append HTML only once!
document.getElementById("loopResults").innerHTML = loopOutput;
}
showResults();
<div id="loopResults"></div>
答案 4 :(得分:0)
在循环内移动随机计算但不是变量初始化。
var x = 0;
function showResults() {
var randomNum;
loopOutput = "";
while (x < 10) {
randomNum = Math.floor(Math.random() * 999) + 1;
document.getElementById("loopResults").innerHTML += "<p>Our answer: " + x + ". " + randomNum + "</p>";
x++;
}} //end function showResults()