【问题标题】:Javascript Mini Game with Arrays带有数组的 Javascript 小游戏
【发布时间】:2020-10-06 21:47:00
【问题描述】:

我正在尝试一个非常简单的带有 javascript 的游戏“石头、纸或剪刀”。 (主要是为了学习函数,虽然我认为我的代码很有意义,它应该在控制台中打印每个 If Else 语句的输出,但它不会打印任何内容。

有什么提示吗?

代码如下

const startGame = document.getElementById('start-game-btn');
const choicePlayer = ["Rock" , "Scissor", "Paper"];
const defaultChoise = "Rock";


function startTheGame(choicePlayer,defaultChoise) {

alert("Choose Rock , Scissor or Paper");

prompt(choicePlayer[0], choicePlayer[1]);

for (var i=0; i<choicePlayer.length; i++)  {
if(choicePlayer[i]===choicePlayer[0] || choicePlayer[i] === choicePlayer[1] || choicePlayer[i] === choicePlayer[2]) {
    console.log("asdf");
    return choicePlayer[i];

}

else  {

console.log("we choose for you");
return defaultChoise;

}
}

}


startGame.addEventListener('click' , startTheGame);

【问题讨论】:

    标签: javascript arrays function


    【解决方案1】:

    prompt 通过返回一个值来工作,这意味着您应该像这样使用它:

    choicePlayer[0] = prompt("Player 1 - Choose Rock , Scissor or Paper", choicePlayer[0]);
    
    choicePlayer[1] = prompt("Player 2 - Choose Rock , Scissor or Paper", choicePlayer[1]);
    

    另外 - 有一个名为 choicePlayer 的函数参数将覆盖您的全局变量 choicePlayer,这意味着函数内的 choicePlayer 包含 event 参数。

    【讨论】:

    • 非常感谢!我对此很陌生!所以要么我在函数内部创建选择数组,要么我只是不将它用作函数 () 的参数?
    【解决方案2】:

    为了保存来自prompt 函数的用户输入,您应该将其保存在一个变量中,如下所示:const result = prompt("text that will show in the prompt"); 您可以查看我添加的 sn-p 以获得其他一些修复的解决方案。

    const startGame = document.getElementById('start-game-btn');
    const choices = ["rock" , "scissor", "paper"];
    const defaultChoice = "rock";
    
    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
    
    function gameInit() {
    
      const playerChoice = prompt("Choose Rock , Scissor or Paper");
    
      if(choices.includes(playerChoice.toLowerCase())) {
        //return playerChoice;
        console.log(capitalizeFirstLetter(playerChoice));
      } else  {
        console.log("we choose for you");
        //return defaultChoice;
        console.log(capitalizeFirstLetter(defaultChoice));
      }
    
    }
    
    
    startGame.addEventListener('click' , gameInit);
    &lt;button id="start-game-btn"&gt;Start&lt;/button&gt;

    【讨论】:

    • 非常感谢先生!尽管使用了语句 return string.charAt(0).toUpperCase() + string.slice(1); ,但它的作用就像一个魅力。让我有点困惑
    • 这是一个字符串大写的函数。它需要将字符串的第一个字母变成大写字母,然后连接字符串的其余部分
    • 酷!但我认为我们也可以在提示功能上使用 toUpperCase() 方法?像 Const playerChoice = prompt("Choose Rock , Scissor or Paper").toUpperCase() 也是怎么回事,你不需要 for 循环来浏览数组的所有选项,所以函数可以检查每个选项?
    • toUpperCase 方法会将所有字符串转换为大写字母。我使用includes 方法检查玩家选择是否在数组中
    猜你喜欢
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2012-03-10
    • 2018-01-24
    相关资源
    最近更新 更多