JavaScript while循环无法正常运行

时间:2019-09-30 07:15:12

标签: javascript function loops while-loop

我正在尝试为我的编程课入门做此作业,但无法正常运行。假设发生的是,当currTime小于50时,减去5并显示剩余金额。

function display(){
    var currTime = 50;

    while(currTime < 50){
        currTime -= 5;
        document.write("Time remaining: " + currTime + "</br>");
    }

    if(currTime = 25){
        alert("Warning Less than ½ way to launch, time left " + currTime)
    } else if(currTime == 0){
        alert("Blast Off!!! <img src='RocketLaunch.gif' />"); 
    }
}

display();

5 个答案:

答案 0 :(得分:1)

我假设这是您想要做的,有两个问题,如您从评论中看到的。

function display(){
  var currTime = 50;

  // This should probably run as long as `currTime` is greater than `0`.
  while(currTime > 0) { 
    currTime -= 5;
    console.log("Time remaining: " + currTime + "</br>");

    // Move this `if` inside the while.
    if(currTime == 25){ // replace `=` with `==` for an equality check
        console.log("Warning Less than ½ way to launch, time left " + currTime)
    } else if(currTime == 0){
        console.log("Blast Off!!! <img src='RocketLaunch.gif' />"); 
    }    
  }
}

display();

我将document.writealert的调用替换为console.log,因为在调试时更方便用户使用...

答案 1 :(得分:0)

在while循环中更改条件。不要返回document.write并创建函数显示。在循环中移动if语句

var currTime = 50;

function display() {
  while (currTime <= 50 && currTime >= 5) {
    currTime -= 5;
    document.write("Time remaining: " + currTime + "</br>");
    if (currTime == 25)
      console.log("Warning Less than ½ way to launch, time left " + currTime)
    else if (currTime == 0)
      console.log("Blast Off!!! <img src='RocketLaunch.gif' />");
  }

}
display();

答案 2 :(得分:0)

只需更改您的第一个while语句,因为它会导致错误的值
     while(currTime <50)使它反转while(currTime> 50),它将开始工作。

答案 3 :(得分:-1)

  1. 循环不会开始
  2. 即使您将currTime = 49或更小,循环也不会结束。您必须指定一些内容才能结束循环。

答案 4 :(得分:-1)

请尝试使用currTime < 50,因为currTime <= 50是False,而不是50<50