在我达到5之前,无法让我的脚本打印随机数

问题描述 投票:0回答:2

我的任务是打印出随机数,直到我得到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";
  }
}
javascript loops random
2个回答
0
投票

如果您不想在两次通话之间等待,可以使用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>

1
投票

这假设您需要打印5,否则只需使用while

let x;
do {
  x = Math.ceil(Math.random() * 6);
  document.getElementById('output').innerHTML = x;
} while (x !== 5)
© www.soinside.com 2019 - 2024. All rights reserved.