Javascript如果else返回TRUE或仅返回FALSE

时间:2015-04-03 14:38:18

标签: javascript html5 function if-statement

<body>
<input id ="guessNumber" type="text">
<button id="button" onclick="check()">click here</button>



<script language="javascript" type="text/javascript">
var randomNumber = Math.floor((Math.random()*6));
var guessNumber = document.getElementById("guessNumber").value;

function check() {
    if(guessNumber==randomNumber){
        alert("you are correct");
    }
    else {
        alert("you are wrong");
    }
}
</script>
</body>

我想写一个小编号的游戏程序,我输入一个数字,如果Math.random方法值相等,它应该提醒&#34; TRUE&#34;但它只是警告&#34; FALSE&#34;(&#34;它是错误的&#34;我的警报代码)。给我一个解释为什么这不仅仅是答案,为什么guessNumber变量是一个字符串?

2 个答案:

答案 0 :(得分:4)

这一行不在函数范围内。

var guessNumber = document.getElementById("guessNumber").value;

它获取一次值,它不会随着文本的变化而更新。将其移到方法内。

第二个问题,您正在比较数字和字符串。输入的值是一个字符串。您正在尝试比较数字和字符串。在控制台中输入console.log("3"===3);

&#13;
&#13;
var randomNumber = Math.floor((Math.random() * 6));

function check() {

  var guessNumber = parseInt(document.getElementById("guessNumber").value, 10);
  if (guessNumber === randomNumber) {
    alert("you are correct");
  } else {
    alert("you are wrong");
  }
}
&#13;
<input id="guessNumber" type="text">
<button id="button" onclick="check()">click here</button>
&#13;
&#13;
&#13;

也许如果您运行这样的测试,您就会明白

&#13;
&#13;
var randomNumber = Math.floor((Math.random() * 6));

var initialValue = document.getElementById("guessNumber").value;
var currentValue;

function check() {

  currentValue = document.getElementById("guessNumber").value;
  alert("initialValue: " + initialValue + " | currentValue: " + currentValue + " | randomNumber : " + randomNumber);
  
  var guessNumber = parseInt(currentValue, 10);
  if (guessNumber === randomNumber) {
    alert("you are correct");
  } else {
    alert("you are wrong");
  }
}
&#13;
<input id="guessNumber" type="text" value="INITIAL VALUE">
<button id="button" onclick="check()">click here</button>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

guessNumber是一个字符串,randomNumber是一个数字。试试这个:

function check() {
    if(guessNumber==randomNumber){
        alert("you are correct");
    }
    else {
        alert("you are wrong");
    }
}

https://stackoverflow.com/a/359509/2690289