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

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

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 Denunciar

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 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