我的任务是打印出随机数,直到我得到5,然后停止循环。我尝试在网上搜索,但无法真正找到解决方案。我还在学习基础知识,如果对此有所回答,请不要找到答案。这是我试过的:
function myFunction() {
let x = Math.floor(Math.random() * 6) + 1;
if (x !== 5) {
document.getElementById('output').innerHTML = x;
} else {
document.getElementById('output').innerHTML = "5";
}
}
如果您不想在两次通话之间等待,可以使用while
。
function myFunction(){
let x=Math.floor(Math.random()*6)+1;
document.getElementById('output').innerHTML=x;
if(x!==5){
setTimeout(myFunction, 500)
}
}
myFunction();
<div id="output"></div>
这假设您需要打印5,否则只需使用while
let x;
do {
x = Math.ceil(Math.random() * 6);
document.getElementById('output').innerHTML = x;
} while (x !== 5)