我应该在这里使用数组而不是随机数生成器吗?

时间:2020-06-30 22:11:18

标签: javascript java html arrays

我正在使用Javascript,HTML和CSS制作记忆游戏。

这是游戏的简短说明:

  • 程序生成一个随机数,该随机数显示在 屏幕。
  • 大约5秒钟后,数字消失,屏幕上出现一个弹出框,要求用户输入他或她刚看到的数字。
  • 如果该数字与先前在屏幕上显示的数字匹配,则会出现一个带有“正确”字样的警告框。如果不是,则会显示一个带有“不,请尝试”文字的警告框。

这是我的问题: 即使输入正确的数字,警告框也会显示“不,请尝试”。

这是到目前为止我编写的代码: (请记住,我尚未实现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{
  }
}

感谢您阅读。

3 个答案:

答案 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');