[英]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.