我重复了很多代码。有没有一种方法可以重用相同的代码而不必再次复制它?

I am repeating a lot of code. Is there a way I can reuse that same code with out having to copy it again?

我正在做一个问答网页。用户选择主题,然后选择该主题的课程,以及要显示的问题数量。问题是从一个数组中选择的。我为不同的主题制作了不同的数组,然后对于数组中的每个对象,我都给它 属性 课程、问题和答案。用户提交请求后,根据用户选择的课程从适当的数组中选择问题,并将其放入另一个数组并打乱。来自此的问题然后显示在 div 中。 我已经编写了根据用户选择的课程提取问题的代码,然后将它们洗牌并多次显示在 html 页面中(针对每个主题)。最终我想扩展我的主题,这意味着我将一次又一次地复制和粘贴几乎相同的代码。 有没有办法让我不需要一直重复这部分?

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">
</head>

<body>

  <div class="selCont">
    <label for="myTopic">Topic:</label>
    <select id="myTopic">
      <option value="">--Select--</option>
      <option value="Biology">Biology</option>
      <option value="Chemistry">Chemistry</option>
      <option value="Physics">Physics</option>
    </select>


      <select id='myBiology' class="lesson-select">
      <option value="">--Select Lesson--</option>
      <option value="Cells">Cells</option>
      <option value="Tissues and organs">Tissues and organs</option>
      <option value="Cell division">Cell division</option>
      </select>

      <select id='myChemistry' class="lesson-select">
      <option value="">--Select Lesson--</option>
      <option value="Atoms, elements and compounds">Atoms, elements and compounds</option>
      <option value="Periodic table">Periodic table</option>
      <option value="Bonding">Bonding</option>
      </select>

      <select id='myPhysics' class="lesson-select">
      <option value="">--Select Lesson--</option>
      <option value="Forces and motion">Forces and motion</option>
      <option value="Energy stores and transfer">Energy stores and transfer</option>
      <option value="Electricity">Electricity</option>
      </select>


    <label for="myNumber">Number of Questions:</label>
    <select id='myNumber'>
    <option value="">--Select--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="5">5</option>
    <option value="10">10</option>
    </select>


    <button class="go-btn" type="submit">Go</button>
  </div>

  <div class="selected" id="q1"></div>
  <div class="selected" id="q2"></div>
  <div class="selected" id="q3"></div>
  <div class="selected" id="q4"></div>
  <div class="selected" id="q5"></div>
  <div class="selected" id="q6"></div>
  <div class="selected" id="q7"></div>
  <div class="selected" id="q8"></div>
  <div class="selected" id="q9"></div>
  <div class="selected" id="q10"></div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="mainjs.js" charset="utf-8"></script>
</body>

</html>

JS


    var biologyQ=[{
        "lesson": "Cells",
        "difficulty": "1",
        "question": "This is q1 for Cells",
        "answer": "This is a1 for Cells"
      },
      {
        "lesson": "Cells",
        "difficulty": "1",
        "question": "This is q2 for Cells",
        "answer": "This is a2 for Cells"
        },
        {
          "lesson": "Cells",
          "difficulty": "2",
          "question": "This is q3 for Cells",
          "answer": "This is a3 for Cells"
        },
      {
        "lesson": "Tissues and organs",
        "difficulty": "1",
        "question": "This is q1 for Tissues and organs",
        "answer": "This is a1 for Tissues and organs"
      }, {
        "lesson": "Tissues and organs",
        "difficulty": "2",
        "question": "This is q2 for Tissues and organs",
        "answer": "This is a2 for Tissues and organs"
      },
      {
        "lesson": "Tissues and organs",
        "difficulty": "2",
        "question": "This is q3 for Tissues and organs",
        "answer": "This is a3 for Tissues and organs"
      }, {
        "lesson": "Cell division",
        "difficulty": "1",
        "question": "This is q1 for Cell division",
        "answer": "This is a1 for Cell division"
      },
      {
        "lesson": "Cell division",
        "difficulty": "2",
        "question": "This is q2 for Cell division",
        "answer": "This is a2 for Cell division"
        },
        {
          "lesson": "Cell division",
          "difficulty": "3",
          "question": "This is q3 for Cell division",
          "answer": "This is a3 for Cell division"
      }
    ];
    
    var chemistryQ=[{
        "lesson": "Atoms, elements and compounds",
        "difficulty": "1",
        "question": "This is q1 for Atoms, elements and compounds",
        "answer": "This is a1 for Atoms, elements and compounds"
      },
      {
        "lesson": "Atoms, elements and compounds",
        "difficulty": "1",
        "question": "This is q2 for Atoms, elements and compounds",
        "answer": "This is a2 for Atoms, elements and compounds"
        },
        {
          "lesson": "Atoms, elements and compounds",
          "difficulty": "1",
          "question": "This is q3 for Atoms, elements and compounds",
          "answer": "This is a3 for Atoms, elements and compounds"
        },
      {
        "lesson": "Periodic table",
        "difficulty": "1",
        "question": "This is q1 for Periodic table",
        "answer": "This is a1 for Periodic table"
      }, {
        "lesson": "Periodic table",
        "difficulty": "2",
        "question": "This is q2 for Periodic table",
        "answer": "This is a2 for Periodic table"
      },
      {
        "lesson": "Periodic table",
        "difficulty": "3",
        "question": "This is q3 for Periodic table",
        "answer": "This is a3 for Periodic table"
      }, {
        "lesson": "Bonding",
        "difficulty": "1",
        "question": "This is q1 for Bonding",
        "answer": "This is a1 for Bonding"
      },
      {
        "lesson": "Bonding",
        "difficulty": "2",
        "question": "This is q2 for Bonding",
        "answer": "This is a2 for Bonding"
        },
        {
          "lesson": "Bonding",
          "difficulty": "3",
          "question": "This is q3 for Bonding",
          "answer": "This is a3 for Bonding"
      }
    ];
    
    var physicsQ=[{
        "lesson": "Forces and motion",
        "difficulty": "1",
        "question": "This is q1 for Forces and motion",
        "answer": "This is a1 for Forces and motion"
      },
      {
        "lesson": "Forces and motion",
        "difficulty": "1",
        "question": "This is q2 for Forces and motion",
        "answer": "This is a2 for Forces and motion"
        },
        {
          "lesson": "Forces and motion",
          "difficulty": "1",
          "question": "This is q3 for Forces and motion",
          "answer": "This is a3 for Forces and motion"
        },
      {
        "lesson": "Energy stores and transfer",
        "difficulty": "1",
        "question": "This is q1 for Energy stores and transfer",
        "answer": "This is a1 for Energy stores and transfer"
      }, {
        "lesson": "Energy stores and transfer",
        "difficulty": "2",
        "question": "This is q2 for Energy stores and transfer",
        "answer": "This is a2 for Energy stores and transfer"
      },
      {
        "lesson": "Energy stores and transfer",
        "difficulty": "3",
        "question": "This is q3 for Energy stores and transfer",
        "answer": "This is a3 for Energy stores and transfer"
      }, {
        "lesson": "Electricity",
        "difficulty": "1",
        "question": "This is q1 for Electricity",
        "answer": "This is a1 for Electricity"
      },
      {
        "lesson": "Electricity",
        "difficulty": "2",
        "question": "This is q2 for Electricity",
        "answer": "This is a2 for Electricity"
        },
        {
          "lesson": "Electricity",
          "difficulty": "3",
          "question": "This is q3 for Electricity",
          "answer": "This is a3 for Electricity"
      }
    ];
    
    $(document).ready(function(){
        $("#myTopic").change(function(){
            $(this).find("option:selected").each(function(){
              var optionValue = $(this).attr("value")
            $(".lesson-select").hide();
            $("#my"+ optionValue).show();
            });
          });
        });
    
    
    $(document).ready(function(){
        $('.go-btn').on('click',
    
        function() {
          if ($('#myTopic').val() == 'Biology')
          {
            var array = biologyQ;
            const lessonSelected = $('#myBiology').val();
            var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });
    
                 {
                    const array = lessonResult;
    
                    function shuffle(array) {
                      for (let i = array.length - 1; i > 0; i--) {
                        let j = Math.floor(Math.random() * (i + 1));
                        let temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                      }
                    return array;
                    };
    
                    const result = shuffle(array);
                 $('#q1').html(result[0].question);
                 $('#q2').html(result[1].question);
                 $('#q3').html(result[2].question);
    
                   var currentVal = $('#myNumber').val();
                   $('.selected').hide().slice(0, currentVal).show();
                  }
          }
    
          else if ($('#myTopic').val() == 'Chemistry')
            {
              var array = chemistryQ;
              const lessonSelected = $('#myChemistry').val();
              var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });
                   {
                      const array = lessonResult;
    
                      function shuffle(array) {
                        for (let i = array.length - 1; i > 0; i--) {
                          let j = Math.floor(Math.random() * (i + 1));
                          let temp = array[i];
                          array[i] = array[j];
                          array[j] = temp;
                        }
                      return array;
                      };
    
                      const result = shuffle(array);
                   $('#q1').html(result[0].question);
                   $('#q2').html(result[1].question);
                   $('#q3').html(result[2].question);
    
                     var currentVal = $('#myNumber').val();
                     $('.selected').hide().slice(0, currentVal).show();
                    }
                  }
    
                  else if ($('#myTopic').val() == 'Physics')
                    {
                      var array = physicsQ;
                      const lessonSelected = $('#myPhysics').val();
                      var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });
                           {
                              const array = lessonResult;
    
                              function shuffle(array) {
                                for (let i = array.length - 1; i > 0; i--) {
                                  let j = Math.floor(Math.random() * (i + 1));
                                  let temp = array[i];
                                  array[i] = array[j];
                                  array[j] = temp;
                                }
                              return array;
                              };
    
                              const result = shuffle(array);
                           $('#q1').html(result[0].question);
                           $('#q2').html(result[1].question);
                           $('#q3').html(result[2].question);
    
                             var currentVal = $('#myNumber').val();
                             $('.selected').hide().slice(0, currentVal).show();
                            }
                          }
    
        else
          {
            $(".selected").hide();
          }
    
          });
        });

css

   

    .selected{
        display:none
    }
    
    .lesson-select{
      display:none
    }

您可以像下面这样简化您的代码:

$(document).ready(function(){
    $('.go-btn').on('click',function() {

        var array = ($('#myTopic').val() == 'Biology' ? biologyQ : ($('#myTopic').val() == 'Chemistry' ? chemistryQ : physicsQ));
        const lessonSelected = ($('#myTopic').val() == 'Biology' ? $('#myBiology').val() : ($('#myTopic').val() == 'Chemistry' ? $('#myChemistry').val() : $('#myPhysics').val()));
        var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });

        {
            const array = lessonResult;

            function shuffle(array) {
                for (let i = array.length - 1; i > 0; i--) {
                    let j = Math.floor(Math.random() * (i + 1));
                    let temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
                return array;
            };

            const result = shuffle(array);
            $('#q1').html(result[0].question);
            $('#q2').html(result[1].question);
            $('#q3').html(result[2].question);

            var currentVal = $('#myNumber').val();
            $('.selected').hide().slice(0, currentVal).show();
        }
    });
});