简体   繁体   中英

Is there a way to simplify this JavaScript code?

I know this is a broad question but I'm still novice to know what to search/ask for.

I have this JavaScript series for a Jeopardy game. I am sure that there is a better way to do this because there is so much repetition. I'm thinking something with some variables, arrays, and/or passing IDs through when the function is called but don't know where to start. Any ideas would be appreciated. I am not asking anyone to do the work, just give me some ideas and examples of which direction to go.

var score = 0;


//Disable the question button
function disableButton(btnID){
        document.getElementById(btnID.id).disabled = true;
    }

//Show current score
function endQuestion(){
  alert ("Your total score is now " +score);
}

//Toggle Images On
function showImgBtn1(){
  document.getElementById('btn1pic').style.visibility = 'visible';
  setTimeout(askQuestion1,3000);
}
function showImgBtn2(){
  document.getElementById('btn2pic').style.visibility = 'visible';
  setTimeout(askQuestion2,3000);
}
//This keeps going for every question--repeated 9 to 20 times


//Questions
function askQuestion1()
{
  var answer = prompt ("What body system contains the heart, blood, arteries, and veins?") .toLowerCase();
   if (answer==="circulatory") {
    alert ("Correct!");
     score += 100;
  }
  else {
    alert ("Sorry, incorrect.");
     score -= 100;
  }
    endQuestion();
    document.getElementById('btn1pic').style.visibility = 'hidden';
}

function askQuestion2()
{
  var answer = prompt ("What body system contains the brain, spinal cord, and nerves?") .toLowerCase();
  if (answer==="nervous") {
   alert ("Correct!");
    score += 200;
  }
  else {
    alert ("Sorry, incorrect.");
    score -= 200;
  }
  endQuestion();
  document.getElementById('btn2pic').style.visibility = 'hidden';
}
//This keeps going for every question--same code, just replace the question and answer repeated 9 to 20 times

This is how I call it on my HTML page:

<td><button id="btn1" onclick="showImgBtn1();disableButton(btn1)">100</button></td> //each button has a successive ID

and this is how I have the pics set up on my HTML page:

<div>
  <img class="picClue" id="btn1pic" src="btn1.jpg" height="200px">
  <img class="picClue" id="btn2pic" src="btn2.jpg" height="200px">
  <img class="picClue" id="btn3pic" src="btn3.jpg" height="200px">
  <img class="picClue" id="btn4pic" src="btn4.jpg" height="200px">
</div>

Thanks for any advice!

I see a few things that you could improve. It is a good things that you notice there is a lot of repetition in your code. First of all, the function askQuestion1 and askQuestion2 does the exact same thing with the exception of a few variable. So you could make one function and store your different value into a object. Something like this :

 let values = { question1: { questionText: "What body system contains the heart, blood, arteries, and veins?", correctValue: "circulatory", id: 'btn1pic' }, question2: { questionText: "What body system contains the brain, spinal cord, and nerves?", correctValue: "nervous", id: 'btn2pic' } } let score = 0; function askQuestion(question) { var answer = prompt(question.questionText); // validate null and check if the answer is correct. if (answer && answer.toLowerCase() === question.correctValue) { alert ("Correct!"); score += 100; } else { alert ("Sorry, incorrect."); score -= 100; } endQuestion(); document.getElementById(question.id).style.visibility = 'hidden'; } function endQuestion() {} askQuestion(values.question1); askQuestion(values.question2);

as Edric pointed out in the comment , it is a good idea to validate that your user did not cancel the prompt, resulting in a null value in your answer variable.

You could even save your question in an array and use a for loop to ask each of them:

    let values = [
      {
        questionText: "What body system contains the heart, blood, arteries, and veins?",
        correctValue: "circulatory",
        id: 'btn1pic'
      },
      {
        questionText: "What body system contains the brain, spinal cord, and nerves?",
        correctValue: "nervous",
        id: 'btn2pic'
      }
    ]
/* ... */
    for(let i = 0; i < values.length; i ++) {
        askQuestion(values[i]);
    }

The same things goes for your showImgBtn function, having a question variable would create less repetition.

 //Toggle Images On function showImgBtn(question){ document.getElementById(question.id).style.visibility = 'visible'; setTimeout(() => { askQuestion(question); },3000); }

Other than that, it seams fine.

I highly encourage you to check the comment aswell, many people are suggesting ways to improve my answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM