Массивы клавиш с переключателем - PullRequest
0 голосов
/ 08 мая 2018

Я пытаюсь получить доступ к своим ключам случайного массива с помощью переключателя на каждой из них. Я хочу разместить переключатель только на массиве клавиш allQuestions[index].anwsers и имеет 3 индексных ключа.

Я не смог сделать это, и это моя работа.

const allQuestions = [{
    question: "Which of them is from compton",
    anwsers: ["Nas", "Tupac", "Omarion", "Kendick"],
    correctAnswer: "Kendrick"
  },
  {
    question: "founder of HipHop",
    anwsers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
    correctAnswer: "Bambata"
  },
  {
    question: "Who won BET Hip Hop Album 2018",
    anwsers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
    correctAnswer: "Kendrick",
  },
  {
    question: "Best Female HipHop Art 2018",
    anwsers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
    correctAnswer: "Nicki"
  }
]

function render() {
  var index, unique;
  var print = '<ul>';
  for (i = 0; i < allQuestions.length; i++) {
    index = Math.floor(Math.random() * allQuestions.length);
  }

  var showQuiz = document.getElementById('showQuiz');
  var showAnswers = document.getElementById('showAnswers');

  showQuiz.style.color = 'red';
  showQuiz.innerHTML = allQuestions[index].question;
  showAnswers.innerHTML = allQuestions[index].anwsers;

  // I'm tryin to ue sthe unshift method here but it' not workin
  showAnswers.unshift('<input type="radio" value="allQuestions.anwsers[]');

}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>

Ответы [ 2 ]

0 голосов
/ 08 мая 2018

Похоже, мы пытаемся использовать функцию Array unshift() для элемента DOM. Я полагаю, что вы пытаетесь создать список радиокнопок для каждого ответа в вашем allQuestions.answers[], это можно сделать с помощью цикла for или карты, например:

Редактируйте , чтобы добавить answersAsHtml и join(" "), что улучшает читабельность и объединяет каждый элемент массива с пробелом вместо запятой по умолчанию.

const allQuestions = [{
    question: "Which of them is from compton",
    anwsers: ["Nas", "Tupac", "Omarion", "Kendick"],
    correctAnswer: "Kendrick"
  },
  {
    question: "founder of HipHop",
    anwsers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
    correctAnswer: "Bambata"
  },
  {
    question: "Who won BET Hip Hop Album 2018",
    anwsers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
    correctAnswer: "Kendrick",
  },
  {
    question: "Best Female HipHop Art 2018",
    anwsers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
    correctAnswer: "Nicki"
  }
]

function render() {
  var index, unique;
  var print = '<ul>';
  for (i = 0; i < allQuestions.length; i++) {
    index = Math.floor(Math.random() * allQuestions.length);
  }

  var showQuiz = document.getElementById('showQuiz');
  var showAnswers = document.getElementById('showAnswers');
  var answersAsHtml = allQuestions[index].anwsers.map(ans => `<input type="radio" value="${ans}">${ans}</input>`).join(" ");

  showQuiz.style.color = 'red';
  showQuiz.innerHTML = allQuestions[index].question;
  showAnswers.innerHTML = answersAsHtml;

}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>
0 голосов
/ 08 мая 2018

Вы пытаетесь записать в элемент HTML, это не массив. Вы, наверное, ищете что-то еще подобное.

showAnswers.innerHTML = allQuestions[index].anwsers.map(function (answer){
        return '<input type="radio" name="answers" value="' + answer + '"/>' + answer
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...