2016-10-17 2 views
-1

Я пытаюсь выяснить, как я могу заполнить свою игру с викториной-угрозой с массивами, поэтому у меня могут возникнуть случайные вопросы. В настоящее время я устанавливаю мои вопросы вот так:случайное заполнение викторины с использованием массивов javascript?

массив чтение как Question ID | Question | Question Options | Correct Answer

var cat1question1easy = ["1", "What color is the sky?", "Red", "Pink", "Blue", "Green", "Bluecorrect"]; 
cat1question1easy.name = "cat1question1easy"; 

    var cat2question2easy = ["2", "What color is grass", "Yellow", "Purple", "Black", "Green", "Greencorrect"]; 
cat1question2easy.name = "cat1question2easy"; 

    var cat3question3easy = ["3", "What color is dirt?", "Brown", "White", "Turqouise", "Gray", "Browncorrect"]; 
cat1question3easy.name = "cat1question3easy"; 

Тогда я храню их в массив для простых вопросов:

var cat1easyquestions = newArray(cat1question1easy, cat1question2easy, cat1question1easy); 

Тогда я тяну мой случайный вопрос для слот «вопрос 1», используя:

var randomcat1easyquestion = cat1easyquestions[Math.floor(Math.random()*items.length)] 

Что приносит мне на мой главный вопрос, если мой HTML на мой вопрос выглядит следующим образом:

<h3></h3> 
<input type="radio" name="" value=""> 
<input type="radio" name="" value=""> 
<input type="radio" name="" value=""> 
<input type="radio" name="" value=""> 

Как я мог заполнить его так тянет данные моего массива так, чтобы он показывает, как:

<h3>What color is the sky?</h3> 
<input type="radio" value="Red"> 
<input type="radio" value="Pink"> 
<input type="radio" value="Blue"> 
<input type="radio" value="Green"> 

Является ли это жизнеспособный способ генерировать случайный совет? или я должен смотреть на лучший маршрут?

+0

Этот массив Javascript перетасовка ответ может помочь вам ... http://stackoverflow.com/questions/2450954/how-to-randomize- shuffle-a-javascript-array – tanaydin

+0

Возможно, я сумасшедший, но вы не можете иметь дефисы в именах переменных JavaScript. – zero298

+0

@ zero298 вы правы, я привык писать на конкретном серверном языке моей компании, но та же структура стоит. –

ответ

1

Я бы предложил использовать другую структуру данных для хранения ваши вопросы и ответы:

var questions = [{ 
    question: "What color is the sky?", 
    answers: ["Blue", "Red", "Pink", "Green"] 
}, { 
    question: "What color is grass?", 
    answers: ["Green", "Yellow", "Purple", "Black"] 
}, { 
    question: "What color is dirt?", 
    answers: ["Brown", "White", "Turqouise", "Gray"] 
}]; 

В этой структуре вы всегда ставите правильный ответ всегда. Когда вы фактически показываете параметры, вы сначала перетасовываете их. Это имеет два преимущества:

  • Вы не должны отдельно отметить, что правильный ответ в вашей структуре данных
  • Пользователь получит параметры в случайном порядке, которые могут быть различными в следующий раз

Кроме того, вам, возможно, не потребуется упоминать номер вопроса. Позиция вопроса в общем массиве определяет число.

Ваш HTML должны иметь этикетки для ответов, а также:

<input type="radio" name="answer" value="" id="a1"><label for="a1"></label> 
<input type="radio" name="answer" value="" id="a2"><label for="a2"></label> 
<input type="radio" name="answer" value="" id="a3"><label for="a3"></label> 
<input type="radio" name="answer" value="" id="a4"><label for="a4"></label> 

Содержание этих меток показывают ответы пользователя.

Вот рабочий код:

// List of questions. First mentioned answer is correct one. 
 
var questions = [{ 
 
    question: "What color is the sky?", 
 
    answers: ["Blue", "Red", "Pink", "Green"] 
 
}, { 
 
    question: "What color is grass?", 
 
    answers: ["Green", "Yellow", "Purple", "Black"] 
 
}, { 
 
    question: "What color is dirt?", 
 
    answers: ["Brown", "White", "Turqouise", "Gray"] 
 
}]; 
 

 
// Generic function to return a shuffled array: 
 
function shuffled(arr) { 
 
    arr = arr.slice(); // shallow copy 
 
    for (var i = 0; i < arr.length; i++) { 
 
     var j = Math.floor(Math.random() * (arr.length - i)) + i; 
 
     [arr[i], arr[j]] = [arr[j], arr[i]]; // swap 
 
    } 
 
    return arr; 
 
} 
 

 
// define variables for some of the HTML elements: 
 
var domQuestion = document.querySelector('#question'); 
 
var domAnswers = Array.from(document.querySelectorAll('input[name=answer]')); 
 
var domNext = document.querySelector('#next'); 
 

 
function displayQuestion() { 
 
    // get a random order for the answers: 
 
    var answers = shuffled(questions[questionId].answers); 
 
    // Display question 
 
    domQuestion.textContent = (questionId+1) + '. ' + 
 
           questions[questionId].question; 
 
    domAnswers.forEach(function (input, i){ 
 
     // Set checkbox value and unselect it 
 
     input.value = answers[i]; 
 
     input.checked = false; 
 
     // Display the answer text 
 
     input.nextElementSibling.textContent = answers[i]; 
 
    }); 
 
} 
 

 
// Initialise and display first question 
 
var questionId = 0; 
 
var correctAnswers = 0; 
 
displayQuestion(); 
 

 
// Respond to a click on the Next button 
 
domNext.addEventListener('click', function() { 
 
    // update correct answer counter: 
 
    var domAnswer = domAnswers.find(input => input.checked); 
 
    if (!domAnswer) return; // nothing was selected 
 
    // update number of correctly answered questions: 
 
    if (domAnswer.value == questions[questionId].answers[0]) correctAnswers++; 
 
    // next question 
 
    questionId++; 
 
    if (questionId >= questions.length) { 
 
     alert('You have answered ' + correctAnswers + 
 
       ' of ' + questions.length + ' questions correctly.'); 
 
     // restart 
 
     questionId = 0; 
 
     correctAnswers = 0; 
 
    } 
 
    displayQuestion(); 
 
});
<h3 id="question"></h3> 
 
<input type="radio" name="answer" value="" id="a1"><label for="a1"></label> 
 
<input type="radio" name="answer" value="" id="a2"><label for="a2"></label> 
 
<input type="radio" name="answer" value="" id="a3"><label for="a3"></label> 
 
<input type="radio" name="answer" value="" id="a4"><label for="a4"></label> 
 
<p> 
 
<button id="next">Next</button>

0

Вы можете сделать что-то подобное. У вас есть многочисленные ошибки в коде, как ссылки на несуществующий массив

var cat1question1easy = ["1", "What color is the sky?", "Red", "Pink", "Blue", "Green", "Bluecorrect"]; 
cat1question1easy.name = "cat1question1easy"; 

var cat1question2easy = ["2", "What color is grass", "Yellow", "Purple", "Black", "Green", "Greencorrect"]; 
cat1question2easy.name = "cat1question2easy"; 

var cat1question3easy = ["3", "What color is dirt?", "Brown", "White", "Turqouise", "Gray", "Browncorrect"]; 
cat1question3easy.name = "cat1question3easy"; 

var cat1easyquestions = new Array(cat1question1easy, cat1question2easy, cat1question3easy); 

Loop через массив для создания входных радиоприемного

var randomcat1easyquestion = cat1easyquestions[Math.floor(Math.random() * cat1easyquestions.length)] 
// create h3 
var createH3 = document.createElement('h3'); 
createH3.textContent = randomcat1easyquestion[1] 
// append it to dom element 
document.getElementById('holder').appendChild(createH3); 
// start looping from 2nd element as first two elemnts are not color 
    for (var i = 2; i <= randomcat1easyquestion.length; i++) { 
    var input = document.createElement('input'); 
    input.type = "radio"; // type of input 
    input.name = "color"; // name is required for radio 
    input.value = randomcat1easyquestion[i]; // assign value like red, blue, etc 
    input.id = 'col_' + i; 
    var label = document.createElement('label'); // label require for radi 
    label.for = 'col_' + i; 
    label.textContent = randomcat1easyquestion[i]; 
    document.getElementById('holder').appendChild(input);// append to dom 
    document.getElementById('holder').appendChild(label) // append to dom 
} 

DEMO

Смежные вопросы