gpt4 book ai didi

javascript - while 循环退出而不是返回循环 -Javascript

转载 作者:行者123 更新时间:2023-11-27 23:25:20 25 4
gpt4 key购买 nike

试图只得到一个数字答案。内部 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 + "!");
}

最佳答案

无需进入循环。

一个简单的例子

// 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 场比赛。你可以通过除以得到这个

关于javascript - while 循环退出而不是返回循环 -Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35004371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com