I'm trying to optimize my code which currently consists of 10 variables and 10 functions. Each function is responsible for retrieving a specific variable and displaying it on an HTML page when a button is clicked. I want to use JavaScript to store the variables in an array and then create a loop to determine which button was clicked and retrieve the corresponding answer.
Although I am new to JavaScript, I believe creating an array is as simple as:
var names = ["var0", "var1", "var2"...];
The initial code I have looks like this:
var ans0 = "echo";
var ans1 = "candle";
var ans2 = "map";
var ans3 = "the letter r";
function answer0(){
document.getElementById("question1").innerHTML = ans1;
}
function answer1(){
document.getElementById("question2").innerHTML = ans2;
}
function answer2(){
document.getElementById("question3").innerHTML = ans3;
}
function answer3(){
document.getElementById("question4").innerHTML = ans4;
}
I know this approach can work, I just need some assistance with the syntax and logic.
In addition to that, here is a snippet of my HTML code:
<div class="questions">
<p class="question">1. I speak without a mouth and hear without ears. I have nobody, but come alive with wind. What am I?</p><!-- echo -->
<div class="answer-btn">
<input type="button" class="get" value="Answer" onclick="answer(0);">
</div><!--/.answer-btn -->
<span class="the-answer" id="question1"></span>
</div><!--/.questions -->
These lines are repeated multiple times throughout my codebase, so finding a more efficient solution would be ideal.