【问题标题】:Is there a way to simplify this JavaScript code?有没有办法简化这个 JavaScript 代码?
【发布时间】:2019-12-17 14:27:05
【问题描述】:

我知道这是一个广泛的问题,但我还是新手,不知道要搜索/询问什么。

我有这个用于 Jeopardy 游戏的 JavaScript 系列。我确信有更好的方法来做到这一点,因为有很多重复。我正在考虑一些变量、数组和/或在调用函数时传递 ID,但不知道从哪里开始。任何想法,将不胜感激。我不是要求任何人做这项工作,只是给我一些想法和例子,告诉我前进的方向。

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

这就是我在 HTML 页面上的称呼:

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

这就是我在 HTML 页面上设置图片的方式:

<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>

感谢您的建议!

【问题讨论】:

  • 不知道从哪里开始... 将所有重复的代码放到一个函数中 - 从 showImgBtn(button, askQuestion, duration) 开始 - 然后以与 @987654325 类似的方式执行此操作@等等..
  • 从数据开始。我认为测验是图片+问题+正确答案的有序(?)列表。想想你的函数来呈现你的页面以将其作为输入。另外,如果您想进行认真的测验 - 不要将答案发送给客户:)

标签: javascript arrays function simplify


【解决方案1】:

我看到了一些你可以改进的地方。您注意到代码中有很多重复是一件好事。首先,函数askQuestion1askQuestion2 做了完全相同的事情,除了一些变量。因此,您可以创建一个函数并将不同的值存储到一个对象中。像这样的东西:

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);

正如Edricthe comment 中指出的那样,最好验证您的用户没有取消提示,从而导致answer 变量中的值为空。

您甚至可以将您的问题保存在一个数组中并使用for 循环来询问每个问题:

    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]);
    }

showImgBtn 函数也是如此,使用 question 变量会减少重复。

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

除此之外,它接缝很好。

我强烈建议您也检查评论,很多人都在建议改进我的答案的方法。

【讨论】:

  • 您没有考虑到用户可能会取消将显示的提示,这会导致您在 null 结果上调用 toLowerCase 时出错。
  • 因为这很危险,我会在values 中为每个问题添加questionScore 作为属性。
  • 谢谢@Nicolas 我明白你在说什么,并将继续努力。我在将数据从 HTML 传递到 JavaScript 时遇到问题,但我认为我在某处输入了错误。也感谢其他评论者。到处都是好主意。
  • ;showImgBtn 不将字符串作为参数,而是将问题对象:showImgBtn(values[0])
  • 但如果您从 HTML 调用它,您可能无法访问 values 变量。因此,您可以使用另一个接受字符串并调用相应问题对象的函数。 function(key) { showImgBtn(values[key]); };
猜你喜欢
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多