我是一个完全的初学者,所以请原谅我缺乏知识。
我有一个多次执行的代码,用户通过提示给出变量的值。有没有办法在每个循环上存储此值并在循环结束时显示它。我应该使用某种元素吗?
谢谢。
var ran = Math.floor(Math.random() * 60) + 1;
var ngs = 9;
var guess = prompt("what's your guess?");
while (ngs > 0) {
if (guess < ran) {
var guess = prompt("nope, that was too low. you have " + ngs + " attempts left. guess again");
ngs = ngs - 1;
} else if (guess > ran) {
var guess = prompt("nope, that was too high. you have " + ngs + " attempts left. guess again.");
ngs = ngs - 1;
} else if (guess == ran) {
alert("gj. you win. your guesses were: ");
}
}
alert("no more attempts. you lose. your guesses were: ");
我最后需要警报来显示用户猜测的内容。
答案 0 :(得分:0)
epascarello在上面的评论中是正确的。我个人会建议把它写成一个字符串,但推送到一个数组也可以。
var ran = Math.floor(Math.random() * 60) + 1;
var ngs = 9;
var guess = prompt("what's your guess?");
var guesses = ""
while (ngs > 0) {
if (guess < ran) {
var guess = prompt("nope, that was too low. you have " + ngs + " attempts left. guess again");
ngs = ngs - 1;
guesses += guess + ' ';
} else if (guess > ran) {
var guess = prompt("nope, that was too high. you have " + ngs + " attempts left. guess again.");
ngs = ngs - 1;
guesses += guess + ' ';
} else if (guess == ran) {
alert("gj. you win. your guesses were: " + guesses);
}
}
alert("no more attempts. you lose. your guesses were: " + guesses);
var ran = Math.floor(Math.random() * 60) + 1;
var ngs = 9;
var guess = prompt("what's your guess?");
var guesses = []
while (ngs > 0) {
if (guess < ran) {
var guess = prompt("nope, that was too low. you have " + ngs + " attempts left. guess again");
ngs = ngs - 1;
guesses.push(guess);
} else if (guess > ran) {
var guess = prompt("nope, that was too high. you have " + ngs + " attempts left. guess again.");
ngs = ngs - 1;
guesses.push(guess);
} else if (guess == ran) {
alert("gj. you win. your guesses were: " + guesses.join(' '));
}
}
alert("no more attempts. you lose. your guesses were: " + guesses.join(' '));
答案 1 :(得分:0)
在if / else中跳过guess变量的重新声明。其次,您可以查看以下链接以获取Array类的描述。 Javascript Array