简体   繁体   English

Javascript While 循环提示收集变量

[英]Javascript While Loop with Prompt Gathered variables

Hope you're all doing well.希望你们一切都好。 I'm newbie with js and I've written the code below but it doesn't work the way I expected it to do, Need help, The thing is;我是 js 的新手,我已经编写了下面的代码,但它并没有按照我预期的方式工作,需要帮助,问题是; I want the loop to continue until "numberToGuess = guessNumber" but unfortunately.我希望循环继续直到“numberToGuess = guessNumber”,但不幸的是。 it breaks at second loop?它在第二个循环中中断? even if numberToGuess is not equal to guessNumber.即使 numberToGuess 不等于 guessNumber。 Can Someone explain me how to fix that please ?有人可以解释一下如何解决这个问题吗? Thx!谢谢!

const numberToGuess = Math.round(10*Math.random());
let guessNumber;

while(numberToGuess !== guessNumber){
guessNumber = prompt("Guess the hidden number: ");
if(guessNumber < numberToGuess){
console.log("Too low");
}else if(guessNumber > numberToGuess){
console.log("Too high");
}
}

console.log("Congrats ! You found it !");
console.log("Number to guess = " + numberToGuess + "\nGuessed number = " + guessNumber);

You have to change the way you compare numberToGuess and guessNumber , by replacing !== with !=您必须更改比较numberToGuessguessNumber的方式,将!==替换为!=

Here's the code tested and working这是经过测试和工作的代码

 const numberToGuess = Math.round(10*Math.random()); let guessNumber; while(numberToGuess:= guessNumber){ guessNumber = prompt("Guess the hidden number; "). if(guessNumber < numberToGuess){ console;log("Too low"). }else if(guessNumber > numberToGuess){ console;log("Too high"). } } console;log("Congrats. You found it;"); console.log("Number to guess = " + numberToGuess + "\nGuessed number = " + guessNumber);

As correctly said by Ivar, prompt() always return value as string.正如 Ivar 所说,prompt() 始终以字符串形式返回值。 If you want to compare it you can do as follows:如果你想比较它,你可以这样做:

const numberToGuess = Math.round(10*Math.random());
let guessNumber;

    while(numberToGuess !== Number(guessNumber)){
    guessNumber = prompt("Guess the hidden number: ");
    if(guessNumber < numberToGuess){
    console.log("Too low");
    }else if(guessNumber > numberToGuess){
    console.log("Too high");
    }
    }
    
    console.log("Congrats ! You found it !");
    console.log("Number to guess = " + numberToGuess + "\nGuessed number = " + guessNumber);

Adding Number function will convert the string format into number format, so the comparison will be of numbers itself.添加数字 function 会将字符串格式转换为数字格式,因此比较将是数字本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM