Home > Software design >  multiple if statements into better structure
multiple if statements into better structure

Time:02-14


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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related