【问题标题】:Number game Javascript数字游戏Javascript
【发布时间】:2018-05-05 17:00:55
【问题描述】:

我正在尝试制作一个数字猜谜游戏,我已经完成了它的基本部分,但我正在尝试对其进行操作,以便它最初存储一个随机数,然后玩家从那里继续猜测直到他们猜对了。如果我应该继续使用 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>

【问题讨论】:

标签: javascript if-statement random


【解决方案1】:

一般性回答

对于条件有两种结果(即正确答案或错误答案)的情况,您应该使用 if/else。

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

性能影响

使用 If/else 语句可能会更高效,因为它不需要评估 yourGuess!=randomNumber 的条件。这是真的,因为我们知道,如果它们不相等,它们一定是不相等的。

这是一个例子,

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

请注意,我们只评估yourGuess==randomNumber 的条件,而不是yourGuess!=randomNumber

【讨论】:

  • 好的,谢谢,但是当我运行代码时,它不允许我再次单击提交。我已经尝试输入 console.log 以查看正确答案是什么,当我输入并单击按钮时没有任何反应。
  • 见我的笔记。您将 yourGuess 保存为输入元素,而不是它的值。
【解决方案2】:

不需要那种可以而且应该使用简单的if/else 来完成的 switch 语句。

需要从元素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-->

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多