[英]change variable to global so the outer alert function can use it
我正在為學校編寫一個JavaScript小游戲(剪刀石頭布),作為一個家庭項目,最近我陷入了困境。 我正在嘗試將原始( let
)變量更改為全局變量,以便外部函數可以看到它們的值。 pScore
的值在每個回合中都會增加,分數會更新。
我試圖將變量從let
更改為var
,但是它不起作用。
const game = () => {
let pScore = 0; //player score
let cScore = 0; //computer score
var mScore = 12; // maximal score
// the Function
const updateScore = () => {
const playerScore = document.querySelector(".player-score p");
const computerScore = document.querySelector(".computer-score p");
playerScore.textContent = window.pScore;
computerScore.textContent = cScore;
};
//Check for Paper
if (playerChoice === "paper") {
if (computerChoice === "scissors") {
winner.textContent = "computer wins! :(";
cScore++;
updateScore();
return;
} else {
winner.textContent = "you won! :)";
pScore++;
updateScore();
if (pScore === mScore) {
finalScore();
}
return;
}
}
};
//The Outer function
function timer() {
var countDown = new Date(Date.now() + 60000).getTime();
var x = setInterval(
function () {
var now = new Date().getTime();
var distance = countDown - now;
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timer").innerHTML = seconds;
if (distance < 0) {
clearInterval(x);
alert(un + ' Time is up!' + alert(playerScore.textContent));
location.reload(true);
}
}, 1000
);
}
錯誤:未定義pScore或playerScore
我希望倒數計時功能達到pScore,然后提醒最后更新的分數。
我已經稍微重新排列了您的代碼以使其正常工作。
變化
window.
來自window.pScore
一部分。 pScore變量不是真正的全局變量,而是game()
函數中的全局變量。 playerScore
和computerScore
變量移出game()
函數,並使它們可用於timer()
函數 const playerScore = document.querySelector(".player-score p");
const computerScore = document.querySelector(".computer-score p");
const game = () => {
let pScore = 0; //player score
let cScore = 0; //computer score
var mScore = 12; // maximal score
// the Function
const updateScore = () => {
playerScore.textContent = pScore;
computerScore.textContent = cScore;
};
//Check for Paper
if (playerChoice === "paper") {
if (computerChoice === "scissors") {
winner.textContent = "computer wins! :(";
cScore++;
updateScore();
return;
} else {
winner.textContent = "you won! :)";
pScore++;
updateScore();
if (pScore === mScore) {
finalScore();
}
return;
}
}
};
//The Outer function
function timer() {
var countDown = new Date(Date.now() + 60000).getTime();
var x = setInterval(
function () {
var now = new Date().getTime();
var distance = countDown - now;
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timer").innerHTML = seconds;
if (distance < 0) {
clearInterval(x);
alert(un + ' Time is up!' + alert(playerScore.textContent));
location.reload(true);
}
}, 1000
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.