Home > database >  im doing a guess the number project but my if else doesn't seem to work properly. what am i doi
im doing a guess the number project but my if else doesn't seem to work properly. what am i doi

Time:09-07

its not showing the first message when the results do match it only ever shows the message for when you have lost.

I have tweaked it and it ends up being a thing where it either always says you win even though it tells you what you have guessed doesn't match

JS Code


function play(){
  let random = Math.floor(Math.random() * 3   1)
  let guess = document.querySelector('#myguess').value;
  let pick = document.querySelector('#pick');

  if (guess.value === random){
    pick.innerText = 'You picked ' guess " the result was " random " Congrats!, you guessed correctly"
  }
  else {
    pick.innerText = 'You picked ' guess " the result was " random " Looks like you guessed incorrectly! Sorry :("
  }
}

document.getElementById('btn').addEventListener("click", play)

html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Guess the number</title>
    <!-- stylesheet -->
    <link rel="stylesheet" href="/Users/leon/Desktop/Webdevelopment/guessinggame/guessstyles.css">
    <!-- global fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto Mono&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fork-awesome/1.2.0/css/fork-awesome.min.css" integrity="sha512-aupidr80M36SeyviA/hZ2uEPnvt2dTJfyjm9y6z1MgaV13TgzmDiFdsH3cvSNG27mRIj7gJ2gNeg1HeySJyE3Q==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <!-- font awesome -->
  </head>
  <body>
    <div >
      <div >
        <h2>Pick A Number between 1 and 3</h2>
      </div>
      <div >
        <input type="number" id="myguess">
        <button id="btn" onclick="play()">Submit</button>
      </div>
      <div >
        <p id="pick">Let's see if you picked the correct number?</p>
      </div>
    </div>
  </body>
  <script src="/Users/leon/Desktop/Webdevelopment/guessinggame/guessindex.js"></script>
</html>

CodePudding user response:

In this comparison:

if (guess.value === random){
  • guess is a string
  • guess.value is undefined
  • random is a number
  • === checks for type equality as well as value equality

First of all, drop the .value because that isn't a property on a string. Aside from that, you can do a weaker non-type-checking comparison:

if (guess == random){

Or you could convert the types, such as by parsing the string as a number:

if (parseInt(guess) === random){
  • Related