虽然循环退出而不是返回循环-Javascript

时间:2016-01-25 23:23:41

标签: javascript loops while-loop

尝试只获得一个答案。内部while循环退出而不是返回循环。我不知道为什么。

var numPlays = prompt("How many games do you want to play?");
if (isNaN(numPlays) == true) {
    while (isNaN(numPlays) == true) {
        numPlays = prompt("That's not a number. Please pick a number.");
    }
} else if (numPlays == 0) {
    while (numPlays == 0) {
        numPlays = prompt("You have to at least play one game. Please pick a number.");
    }
} else if (numPlays == 1) {
    alert("OK! Let's play " + numPlays + " game!");
} else {
    alert("OK! Let's play best of " + numPlays + "!");
}

4 个答案:

答案 0 :(得分:1)

无需进入循环。

一个简单的例子

// Wrap in a function so we can start over
function start() {
  var numPlays = prompt("How many games do you want to play?");
  // edited this to check for 0
  if (isNaN(numPlays) || numPlays == 0) {
    alert('Nope, bad answer, try again!');
    return start();
  } else if (numPlays == 1) {
    alert('Ok, lets play 1 game!');
  } else {
    alert('Ok, lets play the best of ' + numPlays + 'games!');
    // A little aside
    // var neededToWin = (Math.floor((numPlays / 2)) + 1);
    // alert('Ok, you need to win ' + neededToWin + ' out of ' + numPlays + ' games to beat me!');
  }
}

从技术上讲,你会想要半数游戏中的最佳游戏+ 1'。 所以要赢,你需要赢得7/12场比赛。您可以通过划分

来找到它

答案 1 :(得分:0)

空输入将评估为 false (在while循环中为'ok')。

尝试使用 parseInt(),对于空字符串和非数字返回 NaN ,使用以下方法测试一些自己的示例:

isNaN(parseInt(prompt("enter number")))

答案 2 :(得分:0)

由于if / elseif结构;只有其中一个可以匹配。它第一次运行时,它要求第1行的数字,然后决定if / elseif / else结构的哪个分支通过。您之后更改numPlays的价值并不重要,决定已经做出决定!

你可能想在这里进行递归调用。

function getNumPlays(message) {
    if (!message) { message = "How many games do you want to play?"; }
    var numPlays = parseInt(prompt(message), 10);
    if (isNaN(numPlays)) {
        return getNumPlays("That's not a number.");
    } else if (numPlays < 1) {
        return getNumPlays("You have to at least play one game.");
    }
    return numPlays;
}
var numChosen = getNumPlays();
if (numPlays === 1) {
    alert("OK! Lets play " + numChosen + " game!");
} else {
    alert("OK! Let's play best of " + numChosen + "!");
}

PS:注意那里的parseInt(..., 10)。这会转换为数字或NaN。 &#39; 10&#39;部分很重要;它指定了数字所在的基数。八进制数字写成&#34; 011&#34;,有时javascript引擎不知道你是否想要八进制或十进制。

答案 3 :(得分:0)

var numPlays = prompt("How many games do you want to play?");


while (isNaN(numPlays) == true || numPlays == 0) {

        if(isNaN(numPlays) == true)
            numPlays = prompt("That's not a number. Please pick a number.");
        else    
            numPlays = prompt("You have to at least play one game. Please pick a number.");
   }

if (numPlays == 1) 
    alert("OK! Let's play " + numPlays + " game!");
else 
    alert("OK! Let's play best of " + numPlays + "!");

我们必须拥有所有这些嵌套循环......这是一项要求吗?我们可以让它变得更简单吗?