gpt4 book ai didi

javascript - 将变量更改为全局变量,以便外部警报功能可以使用它

转载 作者:行者123 更新时间:2023-11-27 23:24:48 28 4
gpt4 key购买 nike

我正在用 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,然后 Alert 最后更新的分数。

最佳答案

我稍微重新安排了您的代码以使其正常工作。

变化

  • window.pScore 中删除了 window. 部分。 pScore 变量不是真正的全局变量,而是 game() 函数中的全局变量。
  • playerScorecomputerScore 变量移出 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
);
}

关于javascript - 将变量更改为全局变量,以便外部警报功能可以使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57840322/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com