首页 > 解决方案 > 在提示中输入石头、纸或剪刀后在控制台中未定义

问题描述

        <script>


           console.log("enter \game()\ to start the game");


            function computerPlay(){
                let a = ['rock','paper','scissors'];
                let b = a[Math.floor(Math.random * a.length)];
                return b;
            }


            function humanPlay(){
                let c = prompt('rock,paper or scissors');
                return c;
          }


            function playRound ( computerSelection,humanSelection){
                if (computerSelection == humanSelection) {
                    console.log("Its a tie");


                }


               if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'paper') {
                   return 'human wins';

               } 

               else if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'scissors') {
                   return 'computer wins';

               } 

               else if ( computerSelection == 'paper' && humanSelection.toLowerCase() == 'rock') {
                   return 'computer wins';

               } 

               else if (computerSelection == 'paper' && humanSelection.toLowerCase() == 'scissors') {
                   return 'human wins';

               } 

               else if (computerSelection == 'scissors' && humanSelection.toLowerCase() == 'rock') {
                   return 'human wins';

               } 

               else if (computerSelection == 'scissors' && humanSelection.toLowerCase() == 'paper') {
                   return 'computer wins'

               } 

               else if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'scissors') { 
                   return 'computer wins';

               } 

            }
            function game(){
                computerSelection = computerPlay();
                humanSelection = humanPlay();
                let results = playRound(computerSelection,humanSelection);
                console.log(results);



            }






        </script>

我一直在尝试从 Odin 项目编写这个简单的游戏 2 小时,但我无法理解为什么代码不起作用。我查看了一些学生的解决方案,并尝试一次又一次地编写我的代码,但似乎每次都不起作用。我在这个脚本中做错了什么?

标签: javascripthtml

解决方案


我认为您的问题出在这一行:

let b = a[Math.floor(Math.random * a.length)];

它应该是:

let b = a[Math.floor(Math.random() * a.length)];

此外,您可以在此处测试您的代码:https ://js.do/

希望能帮助到你!


推荐阅读