边做边切换

时间:2018-12-06 11:16:31

标签: javascript

我想操纵do whileswitch。我有2个选项,分别是“输入”和“退出”。

当我输入选择1时,我想将文本"Option 1"添加到文档中。 但是,直到输入2

,我什么都看不到

var choice = 0;

function main() {

  do {

    document.write("*****MENU*****" + "<br>");
    document.write("1) - Enter " + "<br>");
    document.write("2) - Exit " + "<br>");

    choice = parseInt(prompt("Enter your option please: "));

    switch (choice) {
      case 1:
        document.write("Option 1");
        break;

    }

  } while (choice != 2);

}

2 个答案:

答案 0 :(得分:0)

您错过了调用main()函数的操作。

var choice = 0;

function main()
{

    do{

        document.write("*****MENU*****" + "<br>");
        document.write("1) - Enter " + "<br>");
        document.write("2) - Exit " + "<br>");

        choice = parseInt(prompt("Enter your option please: "));

        switch(choice){
                case 1 :
                        document.write("Option 1");
                break;

        }

    } while(choice != 2);

}
main()         //You missed this

答案 1 :(得分:0)

var choice = 0;

function main() {

  do {

    document.write("*****MENU*****" + "<br>");
    document.write("1) - Enter " + "<br>");
    document.write("2) - Exit " + "<br>");

    choice = parseInt(prompt("Enter your option please: "));

    switch (choice) {
      case 1:
        document.write("Option 1");
        break;
    }
    break; // You Must use break to exit the do while 
  } while (choice != 2);

}

只要指定条件为真,它就会执行代码块。 do ... while 语句,它与while非常相似,主要区别是即使条件永远不为真,do ... while循环也将始终执行一次。