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

Javascript 有没有办法用全局变量来循环?,javascript,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

我有一个序列中的全局变量,比如(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
      }
    }

将每个
数组放入数组中,改用select元素的
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]);
  }
}

改用数组。你真的需要澄清这个问题。让标题描述你的问题,而不是试图把它变成问题,并在你的问题中添加更多的信息——陈述你的期望和正在发生的事情。在了解更多信息之前,请阅读我将如何排列全局变量我了解您是一个新用户,因为您的问题不清楚,您打算实现什么?嗯,(arr)的元素不清楚defined@mhdHD那么,它们在您的原始代码中是如何定义的呢?