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

218
Visualizações
Randomize for loop in javascript

I have a for loop that generates html. I'd for this method to generate the elements randomly. Right now they are cardinally generated i.e. d1, d2, ... di. I want them to follow a random sequence i.e. d1, di, di-3, .. di-k.

         for (let i = numberOfInputs; i < dlArray.length+numberOfInputs; i++){
          html +='\t\t\t\t\t\t<tr>\n'
          html += '\t\t\t\t\t\t<td id="row';
          id   = (1+i-numberOfInputs);
          html += id;
          html +='">\n';
          html += '\t\t\t\t\t\t\t<div id=\"t';
          html += id;
          html +='" class=\"ltarget\">'
          html +='</div>\n' 
          html +='\t\t\t\t\t\t</td >\n'
          html +='\t\t\t\t\t\t<td id=\"d'
          html += id
          html += '\">\n'
          html +=`\t\t\t\t\t\t\t${dlArray[i-numberOfInputs]}\n`;
          html +='\t\t\t\t\t\t\t</td >\n' 
          html +='\t\t\t\t\t\t</tr>\n';
        }

Any help with this would be greatly appreciated. Thanks.

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

0

This is a slightly shorter implementation of the table generator using a Durstenfeld shuffle to generate an arbitrary order of the idx array which is then used to output the elements of the dlArray array:

function shfl(a){
 for(let j,i=a.length;i>1;){
  j=Math.floor(Math.random()*i--);
  if (i!=j) [a[i],a[j]]=[a[j],a[i]]
 }
 return a
}

const dlArray="abcdefghij".split(""),
      idx=[...Array(dlArray.length)].map((_,i)=>i+1);
document.querySelector("div").innerHTML = '<table id="tablestyle">'
 +shfl(idx).map(i=>
   `<td id="row${i}"><div id="t${i}" class="ltarget">${i}</div></td ><td  id="d${i}">${dlArray[i-1]}</td ></tr>`).join("\n")+'</table>';
<div></div>

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