代码之家  ›  专栏  ›  技术社区  ›  Casey Morgan

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

  •  2
  • Casey Morgan  · 技术社区  · 3 周前

    很抱歉,但我对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被重新分配到“摇滚”,并允许我将其传递到playRound。但是,它返回undefined。

    1 回复  |  直到 3 周前
        1
  •  3
  •   user24924388    3 周前

    看见 variable shadowing .

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

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

    或者使用全局变量

    let humanChoice
    
    rock.addEventListener('click', () => {
        humanChoice = "rock"
        playRound()
    });
    
    function playRound() { // remove local variable humanChoice
        // use global variable humanChoice
    }