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

151
Visualizações
multiple if statements into better structure

list.forEach(el, i) {
  var isTrue = true;
  if (isTrue && i == 0) {
    ary[0] = obj.innerText;
  }
  if (isTrue && i == 1) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.innerText;
  }
  if (isTrue && i == 2) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.closest(list[1]).innerText;
    ary[2] = obj.innerText;
  }
  //same pattern continues up to dozens of if statements
})

Hi, I'm new to JS programming. list contains css selectors. obj is DOM element. How can I improve this code?

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

0

All the if statements look superfluous and repetitive - why not just do it all at once? Extract all .textContent from the matching elements, then put the obj.textContent at the end.

const ary = Array.from(
  { length: i - 1 },
  (_, i) => obj.closest(list[i]).textContent
).concat(obj.textContent);

You almost certainly want .textContent, not .innerText.

If the list may not contain the same number of elements as the number of i conditions you have, just slice the array to the desired length before concating on the final obj.textContent.

about 4 years ago · Juan Pablo Isaza Relatório

0

Given the value of isTrue doesn't change, the body can be:

ary[i] = obj.textContent;
while (i--) {
  ary[i] = obj.closest(list[i]).textContent;
}

You likely don't need the forEach loop either, just initialise i to ary.length - 1.

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