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

167
Visualizações
Need to repeat array iteration to make rainbow text

This code I wrote styles the characters of the user input into a rainbow.

function button(){

   var name = window.prompt("Insert your name");

   var namearray = [];

   namearray = Array.from(name);

   let colors = ["red","orange","yellow","green","blue","purple"];

   for(i=0; i < namearray.length; i++){
      element = document.createElement("p");
      elementtext = namearray[i];
      element.innerHTML = elementtext;
      document.getElementById("namediv").appendChild(element);
      element.style.color = colors[i];
   }
}

The problem is that it only colors words up to 6 characters. What I thought of was repeating the iteration of the color array in order to color the rest of the input but I don't know how to apply it.

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

0

Use the % operator:

element.style.color = colors[i % colors.length];
about 4 years ago · Juan Pablo Isaza Relatório

0

when you enter a string larger than the colors array you will access an index that doesn't exist. you need to take the first color and move it to the end:

var name = window.prompt("Insert your name");

var namearray = [];

namearray = Array.from(name);

let colors = ["red","orange","yellow","green","blue","purple"];

for(i=0; i < namearray.length; i++){
  element = document.createElement("p");
  elementtext = namearray[i];
  element.innerHTML = elementtext;
  document.getElementById("namediv").appendChild(element);
  const currentColor = colors.shift(); // take the first color
  colors.push(currentColor); // push it to the end of the array
  element.style.color = currentColor;
}

here is a working example: https://jsfiddle.net/oznw9qeh/

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