Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
How to make two arrays into a single key-value pair dictionary to pass to HTML from JS

I am making a program in which the user presses a button to get a random question and then can press another button to get the answer. I wanted to make a dictionary in JS to contain the questions and answers but couldn't figure out how to do so, so I opted for two arrays; one with the questions and one with the answers. This method works fine but I know there must be a more correct way to accomplish the same thing with a dictionary containing key-value pairs. Here is the JavaScript code:

const questions = Array(
"Question one",
"Question two",
"Question three",
);

const answers = Array(
"Answer one",
"Answer two",
"Answer three",
);

function randomQuestion() {
  const len = answers.length;
  const rnd = Math.floor(Math.random() * len);
  document.getElementById('randomQuestion').value = questions[rnd];
  document.getElementById('randomAnswer').value = answers[rnd];
}

Thank you in advance. I am new to coding so any help is appreciated!

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

class QuestionAnswer {
  QA;
  constructor() {
    this.QA = [];
  }

  AddQuestion(question, answer) {
    this.QA.push({ question: question, answer: answer });
  }

  GetQuestion(index) {
    return this.QA[index];
  }
}

const qa = new QuestionAnswer();
qa.AddQuestion("Q1", "A1");
qa.AddQuestion("Q2", "A2");
qa.AddQuestion("Q3", "A3");

const q1 = qa.GetQuestion(1);
console.log(`Question: ${q1.question} - Answer: ${q1.answer}`);
about 4 years ago · Santiago Gelvez Relatório

0

Melih's answer is correct but without using classes just do this:

const questions = [
{ question: "Question one", answer: "Answer one" },
{ question: "Question two", answer: "Answer two" },
{ question: "Question three", answer: "Answer three" },
];

function randomQuestion() {
  const len = answers.length;
  const rnd = Math.floor(Math.random() * len);
  document.getElementById('randomQuestion').value = questions[rnd].question;
  document.getElementById('randomAnswer').value = questions[rnd].answer;
}
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda