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

165
Vistas
Trying to understand JS loops

I'm struggling with understanding JS loops. I found an online tutorial for a button changing random colors for a div id="container". However, it turns out that the random colors are frequently repeated after a click. I want to change the code and loop through the array colors one by one and change the color of the div#container after each click. This is my code:

let colors = ["blue", "yellow", "green", "brown", "orange"];
let btn = document.getElementById("btn");

btn.addEventListener("click", function () {
  let container = document.getElementById("container");
  for (i = 0; i < colors.length; i++) {
    let selectColor = colors[i];
  }

  container.style.backgroundColor = selectColor;
});

I get the error: assignment to undeclared variable i. Can someone help me out?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You're looping through all the colors in the array at once, and then only use the last one to set the backgroundcolor.

You should only increment by one and then set the color

let colors = ["blue", "yellow", "green", "brown", "orange"];
let btn = document.getElementById("btn");
let i = 0;
let container = document.getElementById("container");

btn.addEventListener("click", function () {
  i++;
  if(i >= colors.length) i = 0;
  container.style.backgroundColor = colors[i];
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to declare the variable i on line 6, so instead of

  for (i = 0; i < colors.length; i++) {
    let selectColor = colors[i];
  }

you would have

  for (let i = 0; i < colors.length; i++) {
    let selectColor = colors[i];
  }
about 4 years ago · Juan Pablo Isaza Denunciar

0

you missed declaring "i" in the for loop.

for(let i = 0; i < colors.length; i++) {
    let selectColor = colors[i];
}
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