使用事件监听器在 JavaScript 中重新分配全局变量

问题描述 投票:0回答:1

抱歉,但我对 JS 相当陌生 - 我正在尝试使用事件侦听器分配“ humanChoice”,然后在函数 playRound 中使用该值。但是,当我将其打印到日志时,尽管我试图分配该值,但该值返回为未定义。任何帮助,将不胜感激。谢谢。

let humanChoice

rock.addEventListener('click', () => {
    humanChoice = "rock"
    playRound()
});

function playRound(humanChoice, computerChoice) {

    if (humanChoice === computerChoice) {
        console.log("It's a tie! There is no winner this round.")
    } else if (humanChoice === "rock" && computerChoice === "paper") {
        computerScore++
        console.log("You lose! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "rock" && computerChoice === "scissors") {
        humanScore++
        console.log("You win! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "paper" && computerChoice === "rock") {
        humanScore++
        console.log("You win! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "paper" && computerChoice === "scissors") {
        computerScore++
        console.log("You lose! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "scissors" && computerChoice === "paper") {
        humanScore++
        console.log("You win! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "scissors" && computerChoice === "rock") {
        computerScore++
        console.log("You lose! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    }
}

我希望 humanChoice 被重新分配给“rock”,并允许我将它传递给 playRound。但是,它返回未定义。

javascript variables event-listener
1个回答
0
投票

请参阅变量范围

您在 playRound 中定义了一个局部变量 humanChoice 作为参数,但在调用它时没有传递任何值。有以下两种解决方案。
作为局部变量传递。

// let humanChoice

rock.addEventListener('click', () => {
    // humanChoice = "rock"
    playRound('rock') // pass 'rock' as parameter
});

function playRound(humanChoice, computerChoice) { // use local variable humanChoice
    // ...
}

或者使用全局变量

let humanChoice

rock.addEventListener('click', () => {
    humanChoice = "rock"
    playRound()
});

function playRound(computerChoice) { // remove local variable humanChoice
    // use global variable humanChoice
}
© www.soinside.com 2019 - 2024. All rights reserved.