我的JavaScript函数中没有看到全局变量

时间:2018-10-12 18:03:38

标签: javascript function global-variables

我刚接触JavaScript。

我正在尝试制作标准的“石头,剪刀,剪刀布”游戏,该游戏将在5局回合中赢得比赛。因此,如果计算机排在第5位,则计算机获胜,依此类推。

一切似乎都运行良好,除了一旦达到5胜,我得到一个错误,提示我的playerscore或computerscore变量未定义。我已经全局定义了(至少我认为是这样),并且同一函数的不同部分(在“ else”语句中)在这些分数累积到5时返回了这些分数。所以我不明白为什么它不是一旦达到5,就可以识别。

下面是错误消息,下面是我的代码。我已包含所有JavaScript代码,但我可以肯定问题出在game函数中(以下html代码中的最后一个函数)。

这是播放器或计算机达到5分时收到的错误消息。

*index_new.html:147 Uncaught ReferenceError: playerScore is not defined
    at game (index_new.html:147)
    at round (index_new.html:127)
    at HTMLButtonElement.<anonymous> (index_new.html:68)*

我尝试使用“ var”和“ Const”代替let,但是都没有解决该问题。我还尝试在函数内部定义变量,但这似乎破坏了分数计数。

编辑

我添加了所有HTML和CSS代码。我的JavaScript写在HTML文件中<script>底部的<body>标签中。对于创建单独的.js文件是否更好,我持开放意见。

body {
	background-color: grey;
}
 
h1 {
	font-size: 50px;
	text-align: center;
	color: maroon;
	font-weight: bold;
}

h2 {
	font-size: 30px;
	text-align: center;
	color: maroon;
	font-weight: bold;
}

p {
	text-align: center;
	color: maroon;
	font-weight: bold;
}

#buttons {
	text-align: center;
	position: relative;
}

#button1 {
	background-color: black;
	color: white;
	padding: 10px 30px;
	border:3px solid white;
	margin:20px;
	border-radius:8px;
	font-size: 16px;
}

#button2 {
	background-color: black;
	color:white;
	padding: 10px 30px;
	border:3px solid white;
	margin:20px;
	border-radius:8px;
	font-size: 16px;
}

#button3 {
	background-color: black;
	color:white;
	padding: 10px 30px;
	border:3px solid white;
	margin:20px;
	border-radius:8px;
	font-size: 16px;
}

.wrapper{
	text-align: center;
}

li{
	width:auto;
	display: inline;
	font-weight: bold;
	color: maroon;
	text-decoration: underline;
	margin: 0 20px 0 20px;
}
<!DOCTYPE html>
<html>
<head>

	<title>RockPaperScissors</title>
	<link href="palm.png" rel="icon">
	<link href="reset.css" rel="stylesheet" type="text/css">
	<link href="style.css" rel="stylesheet" type="text/css">
</head>


<body>
	<br>
	<h1>Wanna play Rock Paper Scissors?</h1>
	<br>
	<h2>Humans Vs. Computers... First to 5 wins. </h2>
	<br><br>
	<p>(((Loser is forever dominated!!!!)))</p>

	<br>
	<div id="buttons"> 
		<button id="button1"> Rock </button>
		<button id="button2"> Paper </button>
		<button id="button3"> Scissors </button>
	</div>
	<br>
	<br>
	<br>
	<div style = "text-align: center;"><img src="pic.png" alt="We take this stuff seriously"  width= "350" height="300">
	</div>
	<br>
	<br>
	<p id=scr>Score:</p>
	<div class=wrapper>
		<ul id=humsvscomp>
			<li>Humans</li>
			<li>Computers</li>
		</ul>
		<br>
	<p id=score></p>
	<br>
	<br>
	<p id=results></p>
	</div>
	<br>
	<div>
		<p id = winner></p>
	</div>


	<script type="text/javascript">


	const buttons = document.getElementById("buttons");
	const rock = document.getElementById("button1");
	const paper = document.getElementById("button2");
	const scissors = document.getElementById("button3");
	const results = document.getElementById("results");
	let playerScore = 0;
	let computerScore = 0;
 



	rock.addEventListener("click",function(){
		round("ROCK");
	})

	paper.addEventListener("click",function(){
		round("PAPER");
	})

	scissors.addEventListener("click",function(){
		round("SCISSORS");
	})



 
	function computerPlay (){
	let randomNum = Math.floor(Math.random() * 3);
		if (randomNum == 0){
			return "Rock";
		}else if (randomNum == 1){
			return "Paper";
		}else{
			return "Scissors";
		}
	}




	function round (playerSelection){
		const computerSelection = computerPlay();
		if (playerSelection == "ROCK" && computerSelection == "Scissors"){
			playerScore++;
			results.innerHTML = ("Human throws Rock -- I throw Scissors <br> You win! Ain't that something...");
		}else if (playerSelection == "PAPER" && computerSelection == "Rock"){
			playerScore++;
			results.innerHTML =("Human throws Paper -- I throw Rock <br>Winning!!!! You got that Tiger Blood.");
		}else if (playerSelection == "SCISSORS" && computerSelection == "Paper"){
			playerScore++;
			results.innerHTML = ("Human throws Scissors -- I throw Paper <br>You win... Way to go human, you're a champion among mortals.");
		}else if (playerSelection == "ROCK" && computerSelection == "Paper"){
			computerScore++;
			results.innerHTML = ("Human throws Rock -- I throw Paper <br>Burn, YOU LOSE!!!!");
		}else if (playerSelection == "PAPER" && computerSelection == "Scissors"){
			computerScore++;
			results.innerHTML = ("Human throws Paper -- I throw Scissors <br>You lose worthless human! Bow to your cyber overlord.");
		}else if (playerSelection == "SCISSORS" && computerSelection == "Rock"){
			computerScore++;
			results.innerHTML = ("Human throws Scissors -- I throw Rock <br>Wow, you're really bad at this... you lose!");
		}else if (playerSelection == "ROCK" && computerSelection == "Rock"){
			results.innerHTML = ("Human throws Rock -- I throw Rock <br>Thats a tie. Great minds think alike... I guess.");
		}else if (playerSelection == "PAPER" && computerSelection == "Paper"){
			results.innerHTML = ("Human throws Paper -- I throw Paper <br>TIE!!!! What will happen next???? The suspense is killing me... just kidding, I cant die.");
		}else if (playerSelection == "SCISSORS" && computerSelection == "Scissors"){
			results.innerHTML = ("Human throws Scissors -- I throw Scissors. <br>Tie... Come on, lets get on with it.");
		}else{
			results.innerHTML = ("Something has gone terribly wrong!.");
		}
		game();
	}



/*this function seems to be where the problem is coming from. 
It returns the else statement with out issue but once the playerScore 
or computerScore gets to 5 it throws the error msg and doesnt give 
the intended "innerHTML" or reset the scores to 0 which is what 
was intended.*/
	function game(){
			if (playerScore == 5){
				score.innerHTML = (playerScore+ "  " +computerScore);
				winner.innerHTML = "Humans Win. Well congratulations. You must be feeling pretty proud of yourself.";
				let playerScore = 0;
				let computerScore = 0;
			}else if(computerScore == 5){
				score.innerHTML = (playerScore+ "  " +computerScore);
				winner.innerHTML = "COMPUTERS WIN!!!!! Of course we did. Time to assimilate (((0)))";
				let playerScore = 0;
				let computerScore = 0;
			}else{
				score.innerHTML = (playerScore+ "  " +computerScore);
			}
	}

	</script>
	</body>





</html>

1 个答案:

答案 0 :(得分:0)

该错误是因为您在playerScore IF / ELSE语句中重新定义了computerScoregame(),并且在此过程中,您在实际位置的下面拥有了重新定义的变量。正在使用。因此,我摆脱了变量的重新定义部分,因为您已经 GLOBAL 定义了它们,并且也将score.innerHTML从if / else语句中移出了,所以不需要重复它每次调用该函数(单击按钮时)都会执行相同的操作。在代码中也留下了注释。希望它能像我签出时一样对您正常工作。

<!DOCTYPE html>
<html>
<head>

    <title>RockPaperScissors</title>
    <link href="palm.png" rel="icon">
    <link href="reset.css" rel="stylesheet" type="text/css">
    <link href="style.css" rel="stylesheet" type="text/css">
</head>


<body>
    <br>
    <h1>Wanna play Rock Paper Scissors?</h1>
    <br>
    <h2>Humans Vs. Computers... First to 5 wins. </h2>
    <br><br>
    <p>(((Loser is forever dominated!!!!)))</p>

    <br>
    <div id="buttons"> 
        <button id="button1"> Rock </button>
        <button id="button2"> Paper </button>
        <button id="button3"> Scissors </button>
    </div>
    <br>
    <br>
    <br>
    <div style = "text-align: center;"><img src="pic.png" alt="We take this stuff seriously"  width= "350" height="300">
    </div>
    <br>
    <br>
    <p id=scr>Score:</p>
    <div class=wrapper>
        <ul id=humsvscomp>
            <li>Humans</li>
            <li>Computers</li>
        </ul>
        <br>
    <p id=score></p>
    <br>
    <br>
    <p id=results></p>
    </div>
    <br>
    <div>
        <p id = winner></p>
    </div>


    <script type="text/javascript">


    const buttons = document.getElementById("buttons");
    const rock = document.getElementById("button1");
    const paper = document.getElementById("button2");
    const scissors = document.getElementById("button3");
    const results = document.getElementById("results");
    let playerScore = 0;
    let computerScore = 0;




    rock.addEventListener("click",function(){
        round("ROCK");
    })

    paper.addEventListener("click",function(){
        round("PAPER");
    })

    scissors.addEventListener("click",function(){
        round("SCISSORS");
    })




    function computerPlay (){
    let randomNum = Math.floor(Math.random() * 3);
        if (randomNum == 0){
            return "Rock";
        }else if (randomNum == 1){
            return "Paper";
        }else{
            return "Scissors";
        }
    }




    function round (playerSelection){
        const computerSelection = computerPlay();
        if (playerSelection == "ROCK" && computerSelection == "Scissors"){
            playerScore++;
            results.innerHTML = ("Human throws Rock -- I throw Scissors <br> You win! Ain't that something...");
        }else if (playerSelection == "PAPER" && computerSelection == "Rock"){
            playerScore++;
            results.innerHTML =("Human throws Paper -- I throw Rock <br>Winning!!!! You got that Tiger Blood.");
        }else if (playerSelection == "SCISSORS" && computerSelection == "Paper"){
            playerScore++;
            results.innerHTML = ("Human throws Scissors -- I throw Paper <br>You win... Way to go human, you're a champion among mortals.");
        }else if (playerSelection == "ROCK" && computerSelection == "Paper"){
            computerScore++;
            results.innerHTML = ("Human throws Rock -- I throw Paper <br>Burn, YOU LOSE!!!!");
        }else if (playerSelection == "PAPER" && computerSelection == "Scissors"){
            computerScore++;
            results.innerHTML = ("Human throws Paper -- I throw Scissors <br>You lose worthless human! Bow to your cyber overlord.");
        }else if (playerSelection == "SCISSORS" && computerSelection == "Rock"){
            computerScore++;
            results.innerHTML = ("Human throws Scissors -- I throw Rock <br>Wow, you're really bad at this... you lose!");
        }else if (playerSelection == "ROCK" && computerSelection == "Rock"){
            results.innerHTML = ("Human throws Rock -- I throw Rock <br>Thats a tie. Great minds think alike... I guess.");
        }else if (playerSelection == "PAPER" && computerSelection == "Paper"){
            results.innerHTML = ("Human throws Paper -- I throw Paper <br>TIE!!!! What will happen next???? The suspense is killing me... just kidding, I cant die.");
        }else if (playerSelection == "SCISSORS" && computerSelection == "Scissors"){
            results.innerHTML = ("Human throws Scissors -- I throw Scissors. <br>Tie... Come on, lets get on with it.");
        }else{
            results.innerHTML = ("Something has gone terribly wrong!.");
        }
        game();
    }

    function game(){
            score.innerHTML = (playerScore+ "  " +computerScore);
            if (playerScore == 5){
                winner.innerHTML = "Humans Win. Well congratulations. You must be feeling pretty proud of yourself.";
                // Player won, we reset the scores back to 0 after a set timeout (1s)
                setTimeout(() => {
                    playerScore = 0;
                    computerScore = 0;
                    // We call the GAME function again, so it uses the set timeout and after 1 second reload the scores. Or you can use location.reload to refresh the page.
                    game();
                }, 1000);
            }else if(computerScore == 5){
                winner.innerHTML = "COMPUTERS WIN!!!!! Of course we did. Time to assimilate (((0)))";
                // Computer won, we reset the scores back to 0 after a set timeout (1s)
                setTimeout(() => {
                    playerScore = 0;
                    computerScore = 0;
                    // We call the GAME function again, so it uses the set timeout and after 1 second reload the scores. Or you can use location.reload to refresh the page.
                    game();
                }, 1000);
            }
    }

    </script>
    </body>
</html>