循环提示,直到用户决定终止程序

时间:2018-01-16 20:14:32

标签: javascript html arrays loops do-loops

这是我的第一篇文章。我正在尝试构建一个基本的js程序,它将提示用户输入一个英雄,看看他们是否在数组中#34;。该程序按预期执行,除了我想要的第一个"做{"之后的提示,以继续提示用户直到用户输入" Q" (是的,我对此非常陌生)。 相反,我的程序在找到英雄后停止提示用户。 谢谢,莎拉。

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script type="text/javascript">
        </script>
    </head>
    <body>
        <script type="text/javascript">

            //Program name: Review
            //Purpose: Allow user to search through array for hero
            // Author: Sarah
            //DLM: 15 Jan 2017
        var more;       //continue looping?
        var hero;       // hero to search for in the array
        var ES = "";    //Space
        var BR = "<br/>"; 
        var ARRAYSIZE = 4;
        var found=false;

        //array of superheroes
        var superheroes = new Array("batman", "superman", "spiderman", "hulk");

        //continue until user wants to quit
        do{ 
            hero = prompt("Enter a hero to see if they are in array.", ES);

            //to lower case
            hero.toLowerCase = hero;

            // loop through heroes, checks if user entered hero is contained within
            for (index=0; index < 4; index++){
                   if (superheroes[index].toLowerCase() == hero){
                        found=true;
                        break;
               }
            }
            if(found){
                document.write(superheroes[index] + " is in the array." + BR)
                quit="Q";
            }else{
                quit = prompt("Hero not found. Do you want to continue? (Y for yes, Q to quit)", ES);
            }
        }while (quit.toUpperCase() != "Q");
 </script>           
    </body>
</html>

4 个答案:

答案 0 :(得分:1)

所以,如果我理解正确,你希望程序继续提示,即使找到了英雄?

在这种情况下,我建议删除此行:quit="Q";

答案 1 :(得分:0)

你辞职是因为:

quit="Q";

在前一行中也缺少分号。

答案 2 :(得分:0)

您的程序因错误而停止。检查你的控制台。

hero.toLowerCase = hero;倒退了。它应该是hero=hero.toLowerCase();此外,您可以使用indexOfincludes来查看英雄是否在数组中,而不是循环播放。

如果您希望该计划要求提供&#34; Q&#34;当发现英雄时,移除其他并将退出提示放在下面,这样每次都会被询问。

&#13;
&#13;
//Program name: Review
//Purpose: Allow user to search through array for hero
// Author: Sarah
//DLM: 15 Jan 2017
var hero; // hero to search for in the array
var ES = ""; //Space
var BR = "<br/>";
var found = false;
var quit;

//array of superheroes
var superheroes = new Array("batman", "superman", "spiderman", "hulk");

//continue until user wants to quit
do {
  hero = prompt("Enter a hero to see if they are in array.", ES);

  //to lower case
  hero = hero.toLowerCase();

  // checks if user entered hero is contained within
  found = superheroes.indexOf(hero) > -1;
  
  if (found) {
    document.write(hero + " is in the array." + BR);
  }

  quit = prompt("Do you want to continue? (Y for yes, Q to quit)", ES);

} while (quit.toUpperCase() != "Q");
&#13;
&#13;
&#13;

答案 3 :(得分:0)

在英雄提示行之后,在do循环内。

if (hero.charAt(0) == 'Q') break;

这将检查英雄的第一个角色是否为大写字母Q. 如果是的话,它就会脱离do while循环并且你已经完成了。