我已决定创建一个小型应用,如果用户正确回答,它会随机为您提供2个数字和一个符号(-或+),它应该console.log('hey');
并显示新的2个数字和一个符号。现在,我的应用仅显示两个数字,即使用户回答正确,也总是说console.log('foo');
。这很简单,但我不明白为什么我可能会丢失某些东西或忘记了,请帮忙!
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Thinking...</title>
</head>
<body>
<div>
<span id="a">A</span> <span id="sign"></span> <span id="b">B</span> =
<label for="result"></label><input type="number" id="result"> <button type="button" id="btn" onclick="checkResult()">press</button>
</div>
<script>
let numberA = document.getElementById('a'),
numberB = document.getElementById('b'),
sign = document.getElementById('sign'),
input = document.getElementById('result');
function checkResult(a, b, sign, result) {
if (sign === '-') {
return a - b;
} else if (sign === '+') {
return a + b;
}
if (result === a-b || result === a+b) {
console.log('hey');
} else if (result !== a-b || result !== a+b) {
console.log('foo');
}
}
function getRandomSign() {
let signs = ['-', '+'];
return signs[Math.floor(Math.random()*signs.length)];
}
function getRandomNumber(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
let aRandom = numberA.innerHTML = getRandomNumber(1, 10);
let bRandom = numberB.innerHTML = getRandomNumber(1, 10);
let signRandom = sign.innerHTML = getRandomSign();
console.log(checkResult(aRandom, bRandom, signRandom, input.value));
</script>
</body>
</html>
答案 0 :(得分:1)
var numberA = document.getElementById('a'),
numberB = document.getElementById('b'),
sign = document.getElementById('sign'),
input = document.getElementById('result');
var aRandom = numberA.innerHTML = getRandomNumber(1, 10);
var bRandom = numberB.innerHTML = getRandomNumber(1, 10);
var signRandom = sign.innerHTML = getRandomSign();
function checkResult() {
let temp;
if (signRandom === '-') {
temp = aRandom - bRandom;
} else if (signRandom === '+') {
temp = aRandom + bRandom;
}
if (temp === parseInt(input.value)) {
console.log('hey');
} else {
console.log('foo');
}
}
function getRandomSign() {
let signs = ['-', '+'];
return signs[Math.floor(Math.random()*signs.length)];
}
function getRandomNumber(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Thinking...</title>
</head>
<body>
<div>
<span id="a">A</span> <span id="sign"></span> <span id="b">B</span> =
<label for="result"></label><input type="number" id="result"> <button type="button" id="btn" onclick="checkResult()">press</button>
</div>
</body>
</html>