Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda