【问题标题】:Can't make my script to print random numbers until I reach 5在我达到 5 之前无法让我的脚本打印随机数
【发布时间】:2019-04-01 12:25:39
【问题描述】:

我的任务是打印出随机数,直到我得到 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";
  }
}

【问题讨论】:

  • 你的数字范围是多少?
  • 这里没有循环。
  • 我的范围是从1到6,至于循环,我尝试使用while和for但没有任何成功。
  • 您的代码中没有for 循环。

标签: javascript loops random


【解决方案1】:

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

let x;
do {
  x = Math.ceil(Math.random() * 6);
  document.getElementById('output').innerHTML = x;
} while (x !== 5)

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 非常感谢,这正是我所需要的。还不能说“已解决”,我会尽快解决。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多