有没有办法用全局变量循环?

时间:2019-01-09 14:12:18

标签: javascript

我在(RoastAboutlvl1 RoastAboutlvl2 RoastAboutlvl3等...)等序列中有全局变量,并且我想要一个全局变量循环

if(lvlOfRoast.value == 1){
      if (selector.options[0].selected) {
        window.alert("choose a topic");
      }else if(selector.options[1].selected){
          document.getElementById("generatedRoast").innerHTML = randomRoast(roastAboutCheapLvl1); // roastAboutCheapLvl1 is a global variable
      }else if (selector.options[2].selected) {
        document.getElementById("generatedRoast").innerHTML = randomRoast(roastAboutCheapLvl2);// roastAboutCheapLvl2 is a global variable
      }else if (selector.options[3].selected) {
        document.getElementById("generatedRoast").innerHTML = randomRoast(roastAboutCheapLvl3);// roastAboutCheapLvl3 is a global variable
      }else if (selector.options[4].selected) {
        document.getElementById("generatedRoast").innerHTML = randomRoast(roastAboutCheapLvl4);// roastAboutCheapLvl4 is a global variable
      }else if(selector.options[5].selected){
        document.getElementById("generatedRoast").innerHTML = randomRoast(roastAboutCheapLvl5);// roastAboutCheapLvl5 is a global variable
      }
    }

1 个答案:

答案 0 :(得分:0)

将每个roastAboutCheapLvl#放入数组中,并使用选择元素的selectedIndex属性,因此当索引不为0时,您可以访问数组中的关联属性:

const arr = [
  roastAboutCheapLvl1,
  roastAboutCheapLvl2,
  roastAboutCheapLvl3,
  roastAboutCheapLvl4,
  roastAboutCheapLvl5
];
if(lvlOfRoast.value == 1){
  const { selectedIndex } = selector;
  if (selectedIndex === 0) {
    window.alert("choose a topic");
  } else {
    document.getElementById("generatedRoast").innerHTML = randomRoast(arr[selectedIndex - 1]);
  }
}