Estou criando um jogo simples de selecionar a resposta correta, a estrutura básica está funcionando, mas gostaria de melhorar o meu código, e aprender a fatorizar melhor.
Segue o trecho que definem as variáveis que uso:
let pos = 0, test, test_status, question, choice, choices, chA,
chB, chC, chD, chE, chF, chG, chH, chI, correct = 0, wrong = 0;
let questions = [
{
question: "Qual dos dois filmes se refere a 'Jornada nas Estrelas'?",
a: "Star Trek",
b: "Star Wars",
c: "ambas as respostas estāo corretas",
d: "ambas as respostas estão incorretas",
answer: "A"
},
{
question: "A frase icônica: 'You bow to no one my friends', foi dito por qual personagem?",
a: "Obi-Wan Kenobi",
b: "Gandalf",
c: "Tex Willer",
d: "Aragorn",
e: "Capitāo America",
f: "Spock",
g: "Nenhuma das opções acima",
answer: "D"
}
E aqui o código relevante a minha pergunta:
question = questions[pos].question;
chA = questions[pos].a;
chB = questions[pos].b;
chC = questions[pos].c;
chD = questions[pos].d;
chE = questions[pos].e;
chF = questions[pos].f;
chG = questions[pos].g;
chH = questions[pos].h;
chI = questions[pos].i;
test.innerHTML = "<h3>"+question+"</h3>";
test.innerHTML += "<label> <input type='radio' name='choices' value='A'> " + chA + "</label><br>";
if (typeof chB !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='B'> " + chB + "</label><br>";
if (typeof chC !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='C'> "+chC+"</label><br>";
if (typeof chD !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='D'> " + chD + "</label><br>";
if (typeof chE !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='E'> "+chE+"</label><br>";
if (typeof chF !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='F'> "+chF+"</label><br>";
if (typeof chG !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='G'> "+chG+"</label><br>";
if (typeof chH !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='H'> "+chH+"</label><br>";
if (typeof chI !== "undefined")
test.innerHTML += "<label> <input type='radio' name='choices' value='I'> "+chI+"</label><br>";
test.innerHTML += "<label></label><br>";
test.innerHTML += "<button onclick='checkAnswer()'>Confirmar Resposta</button>";
O meu editor de texto reclama de duplicação de código tanto na inicialização das variáveis chA, chB ... chI
como na parte que crio o elemento botao no HTML (innerHTML...
). Minha pergunta é, como devo proceder pra eliminar esse emaranhado de código repetitivo, e por tudo num loop, por exemplo?
Um último detalhe: preciso verificar toda vez se a variável em questão não é undefined para evitar o seguinte de ocorrer: