+2

why numberOfGuesses don't work in if statement?

<html> <head> <title>Javascript</title> </head> <body> <p>how many fingers are you holding up?</p> <select id="myNumber"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <button id="button">Guess</button> <script type="text/javascript"> document.getElementById("button").onclick = function () { var myNumber = document.getElementById("myNumber").value ; var guess = Math.floor(Math.random()*6) ; var gotIt=false; var numberOfGuesses = 1 ; while ( gotIt==false) { if (guess==myNumber) { gotIt=true; alert("The number is " + guess + " it took me " + numberOfGuesses + " guesses"); }else{ numberOfGuesses++ ; if(numberOfGuesses==1000){break;} } } } </script> </body> </html>

11/11/2019 5:32:39 AM

Faruk All Hossain

2 Answers

New Answer

+1

You're comparing strings not numbers. Convert your strings into numbers. if (parseInt(guess) == myNumber ) try it now 😅

+1

why i have to convert to number. cause it's already a number(var guess=randomNumber) . by the way. i rewrite my code based on your instruction. but same as before.