dimanche 29 novembre 2020

How to prevent using multiple else if statement in JS?

I have this script that go through my page and looking for any tooltip to fill with the right ingredient. But I would like to know if there is a way to optimize it as it goes like this :

var indiv = document.getElementById("ingredients");
var s = indiv.getElementsByTagName("SPAN"); 
var i;
    
for (i = 0; i < s.length; i++) {
  var ss = s[i].parentElement.textContent;
      
  var ingredient1 = ss.includes("test1");
  var ingredient2 = ss.includes("test2");
 
  if (ingredient1) {
    s[i].textContent = "this is the number 1 ingredient";
  } else if (ingredient2) {
    s[i].textContent = "this is the number 2 ingredien";
  } else {
    s[i].textContent = "unknown ingredient!";
  }
}

And it keeps going with else if (ingredient 3) , else if (ingredient 4) etc.. I know that in Python there is a dictionnary to use but I can't find a good way to do that in JS

Thanks in advance and have a nice day !

Aucun commentaire:

Enregistrer un commentaire