缺少Javascript逻辑

问题描述 投票:-2回答:1

我是这个编码世界的新手,学习Javascript作为第一语言。我正在巩固我目前所收集的javascript技能。我的问题是我的代码中缺少了什么......也许一个指针而不是完整的答案会有帮助。

我的代码的目的是简单地从终端用户那里获得输入,如果用户的输入与我存储在number_to_guess变量中的值相匹配,那么输出应该是 "做得好,聪明的屁股",否则请再试一次,尝试的次数限制为34次。

"请再试一次 "是我遇到麻烦的地方,循环只发生一次。

let number_of_guesses = 0
let number_to_guess = 50
let limit = 4
let guess = prompt("enter a guess")

while (guess != number_to_guess) {
    if (guess != number_to_guess) {
        guess = prompt("enter another guess")
        number_of_guesses = number_of_guesses + 1
    } else {
        console.log("you smart ass")
    }
}

if (number_of_guesses === limit) {
    console.log("you have run out goes")
}
javascript loops variables conditional-statements
1个回答
0
投票

你真的很接近,只是你的while循环有问题。

let number_of_guesses = 0;
let number_to_guess = 50;
let limit = 4;
let guess = prompt("Guess A Number");

while (guess != number_to_guess && number_of_guesses < limit) {

    var remaining = limit - number_of_guesses;

    if (remaining == 1)
        guess = prompt(`Guess Again (Last Chance)`);
    else
        guess = prompt(`Guess Again (${remaining} Tries Remaining)`);

    number_of_guesses = number_of_guesses + 1;

    if (guess == number_to_guess)
        alert("Correct!");
    else if (number_of_guesses == limit)
        alert("Too Many Tries...");
}

0
投票

有一个更好的方法可以不用while循环。这使用递归,是解决这个问题的更有效的方法。

let number_of_guesses = 0 
let number_to_guess = 50  
let limit = 4 

const guess = () => {
    let userGuess = prompt("enter a guess")
    if(parseInt(userGuess) !== number_to_guess){
        number_of_guesses++
        if(number_of_guesses < limit){
            guess()
        } else {
            console.log("you have run out goes")
        }
    } else {
        console.log("you smart ass") 
    }
}
guess()



0
投票

问题在于你的 while 循环条件。你有 while (guess!=number_to_guess);. 由于分号的存在,这有效地缩短了你的while循环,使其成为一个空体。这就是为什么你的循环不能正确运行的原因。试试下面的方法。

let number_of_guesses = 0; 
let number_to_guess = 50;  
let limit = 4; 
let guess = prompt("enter a guess");

while (guess !== parseInt(number_to_guess) && number_of_guesses < limit) {
  guess = prompt("enter another guess");
  number_of_guesses++;
}

if(number_of_guesses===limit) {   
  console.log("you have run out goes");
}
else {
  console.log("you smart ass");
}

0
投票
let number_of_guesses = 0
let number_to_guess = 50
let limit = 3
let guess = prompt("enter a guess")

while (guess != number_to_guess && number_of_guesses<limit) {
   var remaining = limit - number_of_guesses;
    if (guess != number_to_guess) {
        guess = prompt("enter another guess" + remaining)
        number_of_guesses = number_of_guesses + 1
    } 
}

if (number_of_guesses === limit) {
    console.log("you have run out goes")
} else if (guess=number_to_guess) {
  console.log("well done you smarty")
}
© www.soinside.com 2019 - 2024. All rights reserved.