数字游戏JavaScript



我正在尝试做一个数字猜测游戏,我的基本部分是下降的部分直到他们做对。如果我应该继续使用Switch语句,请告诉我,或者我应该回到IF/ELSE语句。

<!DOCTYPE html>
<html>
 <style>
 </style>
  <body>
   <h1 id="prompt">Can you guess the number I am thinking of?</h1>
    <h2 id="prompt2"></h2>
     <input id="guess" type="text" value=""> <!--Box for the input-->
      <input type="button" value="guess" onclick="numberGuess();"><!--Button 
        that exacutes the code-->
  </body>
 <script>
  var randomNumber =Math.floor((Math.random()*10)+1)
  function numberGuess() {
  var number= randomNumber;
  var yourGuess=document.getElementById('guess');
    switch (guesspart) {
      case (yourGuess==randomNumber) :
        console.log('Correct');
        break;
        case (yourGuess!=randomNumber):
          console.log('Correct');
          break;
      default:
      console.log(number);
    }};
    /*if (yourGuess==randomNumber){
      document.getElementById('prompt').innerHTML ='You have guessed 
Correctly';
}
    else (yourGuess!=randomNumber)
      document.getElementById('prompt').innerHTML='Sorry the number was 
  '+randomNumber;
  };*/
   </script>
 </html>

一般答案

对于情况有两个结果的情况(即正确答案或错误的答案),您应该使用时使用。

为了进行比较,您必须将yourGuess设置为document.getElementById('guess').value。现在,您将DOM输入与正确答案(数字)进行比较,该答案将始终失败。

性能含义

使用if/else语句可能更具性能,因为它无需评估yourGuess!=randomNumber的状况。这是真的,因为我们知道,如果它们不等,则必须是不平等的。

一个例子,

if (yourGuess==randomNumber) {
  console.log('Correct');
}
else {
  console.log('Incorrect');
}

请注意,我们仅评估yourGuess==randomNumber的状况,而不是yourGuess!=randomNumber

无需使用简单的if/else

您需要从元素document.getElementBydId('guess').value

获得值

var randomNumber =Math.floor((Math.random()*10)+1)
  function numberGuess() {
  var number= randomNumber;
  var yourGuess=parseInt(document.getElementById('guess').value);
  
  if(yourGuess === randomNumber) {
    console.log("Correct");
  } else {
    console.log("Incorrect");
  }
};
<h1 id="prompt">Can you guess the number I am thinking of?</h1>
    <h2 id="prompt2"></h2>
     <input id="guess" type="text" value=""> <!--Box for the input-->
      <input type="button" value="guess" onclick="numberGuess();"><!--Button 
        that exacutes the code-->

最新更新