【问题标题】:While loop decrements in JavaScript until it reaches 0 and prints "Blastoff"Javascript | While 循环递减直到达到 0 并打印 Blastoff
【发布时间】:2021-03-20 03:59:09
【问题描述】:

我真的需要帮助,因为我完全被困住了。提前谢谢你

运动:

声明一个名为 countdown 的变量并将其赋值为 10。在 while 循环中,每次迭代将 countdown 的值递减一次并打印出来。一旦倒计时达到 0,将“Blastoff”打印到控制台。

到目前为止我做了什么:

var countdown = 10;{
    while (countdown > 0 || 0=== "Blastoff!"){
        console.log(countdown);
        countdown = countdown - 1;
}
    console.log("Blastoff!");
}

这是迄今为止我认为应该是正确的结果:

Output
>>>>Code is incorrect
The first line in your while's block should decrement the value of the variable countdown
10
9
8
7
6
5
4
3
2
1
Blastoff!

【问题讨论】:

  • 反馈的不是很清楚吗?打印前需要先递减。
  • 0=== "Blastoff!"总是为假
  • 或将var countdown = 10;改为var countdown = 9;
  • 我已经尝试过了,它也不起作用。你能指定我应该在哪里以及如何放置它吗?
  • @Cid 如果 OP 在9 声明并初始化countdown,那么显示的第一个数字应该是8,所以你的建议并不能解决问题。

标签: javascript while-loop countdown console.log decrement


【解决方案1】:

非常感谢大家,终于正确了:

var countdown = 10;
while (countdown > 0){
    countdown--;
    console.log(countdown);
}
console.log("Blastoff");

【讨论】:

    【解决方案2】:

    试试这个:

    var countdown = 10
    
    // changed condition to greater than 1
      while (countdown > 1 ){
     
     //printing decremented countdown
      console.log(--countdown)
      
    
    }
      console.log("Blastoff!");

    【讨论】:

    • 这仍然从 10 开始,OP 说这不应该发生。
    【解决方案3】:

    所以只要把代码改成这样:

    var countdown = 10;
    while (countdown > 0){
        countdown--;
        console.log(countdown);
    }
    console.log("Blastoff!");

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2017-04-29
      • 2020-07-31
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多