如何在javascript中的dowhile循环中嵌套if语句

How do you nest if statement in do-while loop in javascript

本文关键字:嵌套 if 语句 循环 dowhile javascript 中的      更新时间:2023-09-26

var temp = 110;
for {
    temp-=1
    if (temp >= 90) {
        console.log("Today's temperature is "+temp+"! "+"Lets go play ball")
    } else {
        console.log("Today's temperature is "+temp+"! "+"It is too hot today to ball!")
    }
    
}while (temp > 90)

请查看我的片段。由于某些原因,它不会运行,因为我已经检查了括号,并指出了一些括号错误。

do而非for

var temp = 110;
do { //its `do` not `for`
  temp -= 1;
  if (temp >= 90) {
    console.log("Today's temperature is " + temp + "! " + "Lets go play ball")
  } else {
    console.log("Today's temperature is " + temp + "! " + "It is too hot today to ball!")
  }
} while (temp > 90);

您可以使用prompt()进行用户输入:

var temp = prompt('Input temperature', '110'); // (message, default input)
console.log('temp', temp);
do { //its `do` not `for`
  temp -= 1;
  if (temp >= 90) {
    console.log("Today's temperature is " + temp + "! " + "Lets go play ball")
  } else {
    console.log("Today's temperature is " + temp + "! " + "It is too hot today to ball!")
  }
} while (temp > 90);

dowhile循环语法如下:

示例

do {
}while(conditions);

因此,带有嵌套if/else语句的do-while循环如下所示:

do while w/nested if/elset

do{
if() {
}
else {
}
}while();

示例w/您的代码

var温度=110;

do {
 if(temp >= 90) 
{
    console.log("Today's temperature is "+temp+"! "+"Lets go play ball");
{
else 
{
    console.log("Today's temperature is "+temp+"! "+"It is too hot today to play      ball!");
}
 temp--; 
} while(temp > 90);

好了,现在让我来解释一下这里发生了什么。本质上,您要做的是告诉编译器做一些事情,直到while循环返回true。所以,如果你注意到我更改了temp -= 1; to temp--;,它完全是一样的——只是使用后者更标准。实际上,您与原始代码非常接近,除了它是一个do-while循环而不是一个for-while。:)

将的替换为do

var temp = 110;
do{
    temp-=1
    if (temp >= 90) {
        console.log("Today's temperature is "+temp+"! "+"Lets go play ball")
    } else {
        console.log("Today's temperature is "+temp+"! "+"It is too hot today to ball!")
    }
}while (temp > 90)

应该是

var temp = 110;
do {
    temp-=1
    if (temp >= 90) {
        console.log("Today's temperature is "+temp+"! "+"Lets go play ball")
    } else {
        console.log("Today's temperature is "+temp+"! "+"It is too hot today to ball!")
    }
    
}while (temp > 90);