如何在javascript

时间:2015-06-26 04:23:38

标签: javascript loops if-statement

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)

请查看我的代码段。因为我已经检查了括号,它不会因某种原因说明某些括号错误。

4 个答案:

答案 0 :(得分:2)

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);




答案 1 :(得分:1)

替换为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)

答案 2 :(得分:1)

应该是

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);

答案 3 :(得分:1)

do while循环语法如下:

示例

do {

}while(conditions);

所以带有嵌套if / else语句的do-while循环是这样的:

do-while w / nested if / else

do{

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

您的代码示例

var temp = 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。 :)