Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
How can I assign forEach to variable? Its possible?

Hello everyone:) I'm trying to write rock, paper, scissors game but I have a little problem. Is there any option to assign let playerChoice = buttons.forEach... to any variable as I did in this code? Unfortunately, it doesn't work like this. I attached my code below.

Thanks for any tips!

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can't use forEach to do what you want here.

First of all, forEach doesn't return anything ever, but second of all, you're returning the button.id.toUpperCase() later, when the user actually clicks the button. Returning from an event handler won't assign the value anywhere useful.

Instead you should add the playerChoice variable in a shared outer scope, and assign to it upon the event.

let playerChoice;
buttons.forEach(button => {
    button.addEventListener('click', () => {
        playerChoice = button.id.toUpperCase();
    });
});

In this way, playerChoice will be updated when the user clicks a button.

However, this probably won't actually help you, because your code won't know that the variable has been updated. So instead, let's create a callback that your event handler can call.

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());
    });
});

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda