我正在使用Javascript,HTML和CSS制作记忆游戏。
这是游戏的简短说明:
这是我的问题: 即使输入正确的数字,警告框也会显示“不,请尝试”。
这是到目前为止我编写的代码: (请记住,我尚未实现setInterval / setTimeout函数。为方便起见,我制作了“隐藏”功能手册。)
JS:
/* game level = easy
numbers from 1-9000 are generated */
function random(a){
a = Math.floor(Math.random() * (9000 - 1) + 1);
document.getElementById("screen").innerText = a;
}
function getInput(a){
var input = window.prompt("Enter the number you just saw:");
if(input === a){
alert("Correct!");
}
else{
alert("Nope. Nice try.");
}
}
/* hide toggle */
function hide() {
var x = document.getElementById("screen");
if (x.style.display === "none") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
我的问题:改用1-9000的数字数组是否理想?
使用数组,我认为我可以做这样的事情:
for(var i = 0; i < arr.length; i++){
if(//){
}
else{
}
}
感谢您阅读。
答案 0 :(得分:1)
据我所知,您将a
视为一个范围大于实际范围的变量。 a
是一个参数,其范围不会超出其声明的功能。
在这种情况下,a
中的random(a)
和a
中的getInput(a)
是两个不相关的实体,其作用域不重叠。
一种解决方案可能是使a
成为全局变量,并在任何函数之外声明它,例如
var a;
function random(){
a = Math.floor(Math.random() * (9000 - 1) + 1);
document.getElementById("screen").innerText = a;
}
function getInput(){
var input = window.prompt("Enter the number you just saw:");
if(input == a){ // make '===' into '==' instead btw
alert("Correct!");
}
else{
alert("Nope. Nice try.");
}
}
答案 1 :(得分:0)
我看到您从用户那里收到一个字符串,但是您尝试将其与一个整数进行比较。因此,假设a = 1,并且输入='1',这意味着它们将永远不相等。
您应该将字符串转换为int,然后进行比较。
答案 2 :(得分:0)
尝试
input == a
代替
input === a
Math.random返回一个数字,您正在将其与具有match类型的字符串进行比较。
console.log(1 === '1');
console.log(1 == '1');