我试图在1-80之间获得8个随机数并将它们放入指定的div中。
var numbers = []
var luckyNumber;
var x = 1;
while (x < 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
for (var i = 1; i < 9; i++) {
document.getElementById('k' + i).innerHTML = numbers[i]
}
numbers.push(luckyNumber);
x++;
}
}
document.write(numbers);
&#13;
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
&#13;
最后2个数字在HTML结果中显示为未定义。但是如果用document.write检查数字,你可以看到最后两个数字。 我该如何解决这个问题?
答案 0 :(得分:1)
您的循环逻辑似乎不正确。您应首先填充数字数组,然后更新html。
var numbers = []
var luckyNumber;
var x = 1;
while (x < 9) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
numbers.push(luckyNumber);
x++;
}
}
for (var i = 1; i < 9; i++) {
document.getElementById('k' + i).innerHTML = numbers[i-1]
}
document.write(numbers);
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
答案 1 :(得分:0)
最简单的解决方法是修复while循环,删除for循环并使用x
找到显示最新数字的div。
var numbers = []
var luckyNumber;
var x = 1;
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
x++;
}
}
document.write(numbers);
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>