添加两个随机数并将总和与用户输入进行比较时,比较始终为假

Comparison always false when adding two random numbers and comparing the sum with user input

我想做的是随机化并将两个数字分配给变量,并在向用户显示变量时添加它们。用户输入两个变量的总和,如果输入和总和相同,则用户获胜。虽然,当我比较时,当我使用 console.log 查看布尔值时,结果总是错误的。 我正在使用 html 和 JavaScript。这是我的代码:

<html>
<head>
<title>
Game A
</title>
<script>
var y = parseInt(Math.floor(Math.random()*20));
var z = parseInt(Math.floor(Math.random()*20));
function myFunction() {
var p = parseInt(document.getElementById("demo"));
var z = parseInt(p);
var x = parseInt(y) + parseInt(z);
var q = parseInt(x);
console.log(z===q?true:false);
if(z===q){
alert("Good job!");
}
else{
alert("aw, try again!");
}
}
</script>
</head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<div id="a" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('a').innerHTML= y;
</script>
</div>
<div id="b" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('b').innerHTML= z;
</script>
</div>
<input id="demo"></input>
<button onclick="myFunction()">Try it</button>

</body>
</html>

您需要使用:document.getElementById("demo").value 从输入中获取值 field.Do 而不是通过将新值重新分配给 [=22= 来更改函数内部 z 的值] 这个:

<html>
<head>
<title>
Game A
</title>
<script>
var y = parseInt(Math.floor(Math.random()*20));
var z = parseInt(Math.floor(Math.random()*20));
function myFunction() {
var p = parseInt(document.getElementById("demo").value);
var z1 = parseInt(p);
var x = parseInt(y) + parseInt(z);
var q = parseInt(x);
  console.log(q); console.log(z1);
console.log(z===q?true:false);
if(z1===q){
alert("Good job!");
}
else{
alert("aw, try again!");
}
}
</script>
</head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<div id="a" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('a').innerHTML= y;
</script>
</div>
<div id="b" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('b').innerHTML= z;
</script>
</div>
<input id="demo"></input>
<button onclick="myFunction()">Try it</button>

</body>
</html>