There is a table and its Stoblots are displayed on the received id . The question is, I feel that this can be done better than I did now, but how? As an option, write to the array and display on the incoming id ?

  for (let i = 0; i < table.length; i++) { switch (id) { case 0: tax[i].style.display = "block"; tax[i].style.display = "none"; tax[i].style.display = "none"; break; case 1: tax[i].style.display = "none"; tax[i].style.display = "block"; tax[i].style.display = "none"; break; case 2: tax[i].style.display = "none"; tax[i].style.display = "none"; tax[i].style.display = "block"; break; } } 
  • 3
    Why are there three assignments in each case ? Only the last will work. - Igor
  • Describe the purpose of the code. Describe what you think should be "better" - speed, compactness, something else? Read the label description [inspection code]. And give pliz the question a normal name reflecting the essence - Kromster
  • Is this code generally working? Give a reproducible example of what this code should do, you can only build guesses. - yolosora

3 answers 3

 var d1 = (id == 0)? "block" : "none"; var d2 = (id == 1)? "block" : "none"; var d3 = (id == 2)? "block" : "none"; for (let i = 0; i < table.length; i++) { // c этими тремя строчками что-то не так, но воспроизведем как в вопросе tax[i].style.display = d1; tax[i].style.display = d2; tax[i].style.display = d3; } 

     const map1 = ['block', 'none', 'none'] const map2 = ['none', 'block', 'none'] const map3 = ['none', 'none', 'block'] table.forEach((row, i) => { tax[i].style.display = map1[id] tax[i].style.display = map2[id] tax[i].style.display = map3[id] }) 

      In your case, you can simply compare the index with id:

       for (let i = 0; i < table.length; i++) { tax[i].style.display = i === id ? 'block' : 'none'; }