Switch语句实现不提供预期的行为

时间:2018-01-07 16:40:31

标签: javascript if-statement switch-statement

我正在使用vanilla JavaScript开发一个quizz应用程序,为了最佳实践,我想确保我遵循D.R.Y.原理

我有五个问题需要检查答案。

结果,我没有使用if语句五次,而是认为我可以像这样实现一个switch语句:

callback.js:

function submitAnswers() {
  var total = 5;
  var score = 0;
  // Get User Input
  var q1 = document.forms['quizForm']['q1'].value;
  var q2 = document.forms['quizForm']['q2'].value;
  var q3 = document.forms['quizForm']['q3'].value;
  var q4 = document.forms['quizForm']['q4'].value;
  var q5 = document.forms['quizForm']['q5'].value;

  // Validation
  for (i = 1; i <= total; i++) {
    if (eval('q'+i) == null || eval('q'+i) == '') {
      alert('You missed question '+ i);
      return false;
    }
  }

  // Set Correct Answers
  var answers = ["d","b","c","a","b"];

  // Check answers
  switch (answers) {
    case q1 == answers[0]:
      score++;
      break;
    case q2 == answers[1]:
      score++;
      break;
    case q3 == answers[2]:
      score++;
      break;
    case q4 == answers[3]:
      score++;
      break;
    case q5 == answers[4]:
      score++;
      break;
  }

  alert('You scored '+score+' out of ' +total);
}

这是index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="css/index.css">
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
        <script type="text/javascript" src="js/callback.js"></script>
        <title>Quiz About the Wonderful World of Fungi</title>

    </head>
    <body>
            <div id="container">
                <header>
                    <h1>Quiz About the Wonderful World of Fungi</h1>
                    <p>Test your knowledge</p>
                </header>
                <section>
                        <div id="results"></div>
                        <form class="myForm" name="quizForm" onSubmit="return submitAnswers()">
                            <h3>1. Roughly how many species of organisms of the kingdom of Fungi have been identified, so far?</h3>
                            <input type="radio" name="q1" value="a" id="q1a">a. 2 Million<br>
                            <input type="radio" name="q1" value="b" id="q1b">b. 37,000<br>
                            <input type="radio" name="q1" value="c" id="q1c">c. 58,000<br>
                            <input type="radio" name="q1" value="d" id="q1d">d. 73,000<br>

                            <h3>2. The process of specifically using mushrooms to break down toxic chemicals and sequester heavy metals is known as:</h3>
                            <input type="radio" name="q2" value="a" id="q2a">a. Bioremediation<br>
                            <input type="radio" name="q2" value="b" id="q2b">b. Mushremediation<br>
                            <input type="radio" name="q2" value="c" id="q2c">c. Mycoremediation<br>
                            <input type="radio" name="q2" value="d" id="q2d">d. Chitinremediation<br>

                            <h3>3. The above-ground part of the mushroom that  we typically associate with a mushroom is only a small part of the whole organism,
                                            as most of it is underground. What is the primary role of this part of the  whole organism?</h3>
                            <input type="radio" name="q3" value="a" id="q3a">a. Nutrient Absorptionn<br>
                            <input type="radio" name="q3" value="b" id="q3b">b. Protection<br>
                            <input type="radio" name="q3" value="c" id="q3c">c. Sexual Reproduction<br>
                            <input type="radio" name="q3" value="d" id="q3d">d. Oxygen Absorption<br>

                            <h3>4. What Is the primary role of a mushroom’s underground mycelium?</h3>
                            <input type="radio" name="q4" value="a" id="q4a">a. Nutrient Absorption<br>
                            <input type="radio" name="q4" value="b" id="q4b">b. Anchoring<br>
                            <input type="radio" name="q4" value="c" id="q4c">c. Asexual Reproduction<br>
                            <input type="radio" name="q4" value="d" id="q4d">d. Protection<br>

                            <h3>5. The largest living organism on earth is thought to be a mushroom (the honey fungus) and it is estimated to be what distance across?</h3>
                            <input type="radio" name="q5" value="a" id="q5a">a. 0.5 mile<br>
                            <input type="radio" name="q5" value="b" id="q5b">b. 2.4 miles<br>
                            <input type="radio" name="q5" value="c" id="q5c">c. 8 miles<br>
                            <input type="radio" name="q5" value="d" id="q5d">d. 0.7 mile<br>
                            <br><br>
                            <input type="submit" name="" value="Submit Answers">
                        </form>

                </section>
                <footer>
                    <p>Copyright &copy; 2017, All Rights Reserved</p>
                </footer>
            </div>
    </body>
</html>

经过测试,我继续得到警告,即使选择了正确的答案,我也有正确的5分。

这里的switch声明不是最佳解决方案吗?我申请错了吗?

3 个答案:

答案 0 :(得分:1)

switch值必须与其中一个案例表达式匹配。 answers永远不会匹配q1 == answers[0]或类似内容。如果您将其更改为switch (true),则switch会起作用,但您仍然只会检查一个答案,而不是全部五个答案(而且它不是很好用{ {1}})。

如果您使用五个不同的switch变量,则需要五个不同的qX语句。但那不是你应该做的。相反,请参阅if评论:

***

几点说明:

  • 声明变量非常重要(您没有声明function submitAnswers() { var total = 5; var score = 0; var i; // *** Note we declare `i` so it's not an implicit global // Get User Input // *** ...as an array var responses = []; for (i = 1; i <= 5; ++i) { responses.push(document.forms['quizForm']['q' + i].value); }; // Set Correct Answers // *** Moved var answers = ["d","b","c","a","b"]; // Validation and check answers both at once for (i = 0; i < responses.length; ++i) { // *** `value` is never `null`, we can just use ! here if (!responses[i]) { alert('You missed question '+ i); return false; } // *** Check response if (response[i] == answers[i]) { ++score; } } alert('You scored '+score+' out of ' +total); } )。如果不这样做,在松散模式下,您最终可能会错误地创建全局变量,这可能很难调试。更多(在我贫血的小博客上的帖子中)*:The Horror of Implicit Globals
  • 每当您到达i以形成evalq1等变量名称时,您可能需要一个数组。 q2有一些有效的用例,但它们很少,而且很少。

答案 1 :(得分:0)

简单的方法。形成一个包含所有选定答案的数组,并使用Array#every

进行迭代比较
var correctanswers = ["d","b","c","a","b"];
var choosenanswers = [q1,q2,q3,q4,q5];
var isallcorrect = choosenanswers.every(function(item,index){
    return item == correctanswers[index];
});
console.log(isallcorrect);

答案 2 :(得分:0)

您可以为此而不是switch语句创建可重用的函数,并使用for循环来检查每个目标值;

&#13;
&#13;
// Answers
var answers = ["a", "b", "c"]

// Correct increments
var correct = 0;

// checkAnswer Function
var checkAnswer = function(question, answer) {
  if (question !== answer) {
    return false;
  }
  return true;
}

var form = document.getElementById('form');

form.addEventListener('submit', function(e) {
  e.preventDefault();

  // Notice length - 1, because we have button element there
  /**
    * If you want to declare variable for each inputs, change 
    * e.target.length and e.target[i].value to your arrays of q/a 
    */
  for (var i = 0; i < e.target.length - 1; i++) {
    if (checkAnswer(e.target[i].value, answers[i]) === false) {
      alert('False answer')
      // Right answer function here
    } else {
      correct++
      alert('Right answer!')
      // False answer here
    }
  }
  alert('Your answer is ' + correct + ' correct out of ' + (e.target.length - 1) + ' questions!');
})
&#13;
<form id="form">
  <input type="text" id="q1">
  <input type="text" id="q2">
  <input type="text" id="q3">
  <button type="submit">Submit answer</button>
</form>
&#13;
&#13;
&#13;