大家好:) 我正在嘗試寫石頭、剪子布游戲,但我遇到了一個小問題。是否有任何選項可以像我在這段代碼中所做的那樣將let playerChoice = buttons.forEach...分配給任何變數?不幸的是,它不是這樣作業的。我在下面附上了我的代碼。
感謝您的任何提示!
let choiceOptions = ["ROCK", "PAPER", "SCISSORS"];
let buttons = document.querySelectorAll('button');
let computerChoice = () => choiceOptions[Math.floor(Math.random() * choiceOptions.length)];
let playerChoice = buttons.forEach(button => {
button.addEventListener('click', () => {
return button.id.toUpperCase();
});
});
console.log(playerChoice) //does not work
uj5u.com熱心網友回復:
你不能forEach在這里做你想做的事。
首先,forEach永遠不會回傳任何東西,但其次button.id.toUpperCase(),當用戶實際單擊按鈕時,您將回傳后者。從事件處理程式回傳不會將值分配到任何有用的地方。
相反,您應該playerChoice在共享的外部范圍中添加變數,并在事件發生時分配給它。
let playerChoice;
buttons.forEach(button => {
button.addEventListener('click', () => {
playerChoice = button.id.toUpperCase();
});
});
這樣,playerChoice當用戶點擊一個按鈕時就會更新。
但是,這實際上可能對您沒有幫助,因為您的代碼不會知道該變數已被更新。因此,讓我們創建一個您的事件處理程式可以呼叫的回呼。
let playerChoice;
let setPlayerChoice = (choice) => {
playerChoice = choice;
// we can use the value of playerChoice now,
// because this callback is being triggered
// by the user clicking the button.
console.log(playerChoice);
}
buttons.forEach(button => {
button.addEventListener('click', () => {
setPlayerChoice(button.id.toUpperCase());
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408036.html
標籤:
