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

336
Visualizações
How to get the value of 'index' and put it on a global variable?

How do I put the value of 'index' to a global variable? The value of the index is showing only if its inside the forEach loop, is there a way to take it out and put it on a global variable?

stars.forEach((star,index) =>{
    star.addEventListener('click', ()=>{
        stars.forEach((star,idx) =>{
            if(idx < index + 1){
                star.classList.add('active');
            } else {
                star.classList.remove('active');
            }
            console.log(index); // this is working
        });
    });    
});
console.log(index); // this is NOT working

Please check thanks!

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

0

First of all, this doesn't seems to be a good idea to do but here you go:

var globalIdx = -1

function fnc() {
  var functionIdx = -1
  stars.forEach((star,index) =>{
    star.addEventListener('click', ()=>{
        stars.forEach((star,idx) =>{
            if(idx < index + 1){
                star.classList.add('active');
            } else {
                star.classList.remove('active');
            }
            console.log(index); // this is working
            globalIdx = index;
            functionIdx = index;
        });
    });    
  });
  console.log(index); // will not work
  console.log(globalIdx); // will work
  console.log(functionIdx); // will work
}
console.log(globalIdx); // will work
console.log(functionIdx); // will not work

Just pick one between functionIdx and globalIdx based on what you need.

Hope this helps :)

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