【问题标题】:Comparison always false when adding two random numbers and comparing the sum with user input添加两个随机数并将总和与用户输入进行比较时,比较总是错误的
【发布时间】:2017-06-06 13:55:36
【问题描述】:

我正在尝试做的是随机化并将两个数字分配给变量,并在向用户显示变量时添加它们。用户输入两个变量的总和,如果输入和总和相同,则用户获胜。虽然,当我比较时,当我使用 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>

【问题讨论】:

  • 因为您在 myFunction 中被重新分配了 z 并在之后添加了 y 。所以当 y 保持为 0 时 q 总是大于 z

标签: javascript html random input addition


【解决方案1】:

您需要使用:document.getElementById("demo").value 从输入字段中获取值。不要通过重新分配新值来更改函数内部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>

【讨论】:

  • 现在我明白了我错过了什么。谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多