Matching elements from two arrays in javascript

2019-06-02 08:21发布

I am trying to make a small random quizz generator, first array has the questions and they are randomly displayed (when page is loaded or when page is refreshed), the second array has the answers.

Now, when the user typed an answer, if that answer is from the answers' array is shown the correct message, even if it is not correct one for that question, and if the answer is not from the answers' array, the not correct message is shown.

I need a code to solve this (I can do it in if...else and with || and && operators, but for more than 5 entries code becomes too long and too hard to maintain) Below javascript and html codes

//reload whole page
function refreshMe() {
    window.location='index.html';
}

const myQs = [
    "How many sides has a hexagon", // must always be the first answer from myRs array
    "A circle has...degrees?", // must always be the second answer from myRs array
    "2^3=...?",
    "2+2:2=..?",
    "A triangle has....degrees?",
    "Square root of 2 is...?" // to be extend up to 500 entries
];


let randomItem = myQs[Math.floor(Math.random()*myQs.length)];

document.getElementById("demo").innerHTML = randomItem;

function userAnswer() {
    const check = document.getElementById('answer').value;

    const myRs = [
        "6",
        "360",
        "8",
        "3",
        "180",
        "1.41"
    ];
    // the difference between 0 and -1?
    if (myRs.indexOf(check) > -1) {
        sayMessage = check + "  is the correct answer!";
    } else {
        sayMessage = check + "  is not the correct answer....";
    }
    document.getElementById("userA").innerHTML = sayMessage;
};

For a random question, now every answer is correct, if a answer out of myRs is typed, the message is not correct. I need a code so that the questions from myQs array to match with its own answer from myRs array, the same index in arrays, first question has first answer, and so on.

I can do it with if...else and || and && operators, but for more than 5 entries the code get too long and too hard for maintaining it.

 <p> The question of the moment...</p>
 <p id="demo"></p>

 <button onclick="refreshMe()">Next one&nbsp;</button><br><br>
 <input name="answer" type="text" placeholder="Your answer is....."     id="answer">
 <br><br>
 <button onclick="userAnswer()">Check answer</button>
 <p id="userA"></p>

3条回答
贪生不怕死
2楼-- · 2019-06-02 08:31

I'd recommend revising the schema of your questions.

Housing questions and answers together within objects would probably be the least error prone approach.

See below for a practical example.

// Questions.
const questions = [
  {q: 'How may sidea has a hexagon', a: 6},
  {q: 'A circle has...degrees?', a: 360},
  {q: '2^3=...?', a: 8},
  {q: '2+2:2=..?', a: 3},
  {q: 'A triangle has....degrees?', a: 180},
  {q: 'Square root of 2 is...?', a: 1.41}
]

// Selected.
const selected = questions[Math.floor(Math.random()*questions.length)]

// Question.
const question = selected.q
document.getElementById('question').innerHTML = question

// Normalise.
const normalise = (number) => Math.round(parseFloat(number), 2)

// Submit Answer.
document.getElementById('form').addEventListener('submit', (event) => {
  event.preventDefault()
  const userAnswer = normalise(document.getElementById('answer').value)
  const actualAnswer = normalise(selected.a)
  const isCorrect = (userAnswer == actualAnswer)
  document.getElementById('feedback').innerHTML = isCorrect && 'Correct                                                                     
查看更多
做自己的国王
3楼-- · 2019-06-02 08:43

Right now you have two lists. One contains questions, the other answers:

var questions = [ "2 + 2", "2 + 1", "1 + 1" ];
var answers = [ "4", "3", "2" ];

In order to easily check your user input, it's a good idea to convert this data structure to an object in which the question is the key, and the answer the value.

Note that this requires your question and answer combinations to be unique. I.e.: a question can not have multiple answers

var questionsWithAnswers = {
  "2 + 2": "4",
  // etc.
}

You can convert the data in javascript, so you don't have to rewrite the lists:

var questionsWithAnswers = {};
for (let i = 0; i < questions.length; i += 1) {
  questionsWithAnswers[question[i]] = answers[i];
}

Now, your check for a question is:

var answerIsCorrect = questionsWithAnswers[question] === userInput;
查看更多
ら.Afraid
4楼-- · 2019-06-02 08:45

First of all, you do understand that having a question and answer available in JS is not a good idea, cause user can see the code.

Anyway, I would combine questions and answer into one structure.

var QAs = [["How many sides has a hexagon", "6"],
    ["A circle has...degrees?", "360"]]; // and so on
let randomItem = QAs[Math.floor(Math.random()*myQs.length)];

document.getElementById("demo").innerHTML = randomItem[0];

function userAnswer() {
    const check = document.getElementById('answer').value;
    if (check == randomItem[1]) {  // check randomItem availability in this scope. otherwise save to to window.randowItem scope.
        sayMessage = check + "  is the correct answer!";
    } else {
        sayMessage = check + "  is not the correct answer....";
    }
    document.getElementById("userA").innerHTML = sayMessage;
}
查看更多
登录 后发表回答