Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

337
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda