0

I have several sets of arrays. Each set begins with the same word:

var firstarrayquestions = ["", "", ""];
var firstarrayanswer1 = ["", "", ""];
var firstarrayanswer2 = ["", "", ""];

var secondarrayquestions = ["", "", ""];
var secondarrayanswer1 = ["", "", ""];
var secondarrayanswer2 = ["", "", ""];

(...etc...)

This may be a question with an obvious solution, but if I want to have one function that handles displaying questions and answers from each array, how would I code that? Something like this:

function handleQuestion(myStr) {
    var randomstart = 0; //just for example
    $('#question').text(myStr + arrayquestions[randomstart]);
    $('#q1').text(myStr + arrayanswer1[randomstart]);
    $('#q2').text(myStr + arrayanswer2[randomstart]);
}

handleQuestion('first');

Many thanks!

1 Answer 1

2

You could use bracket notation if you know the scope, something like

function handleQuestion(myStr) {
    var randomstart = 0; //just for example
    $('#question').text(window[myStr + 'arrayquestions'][randomstart]);
    $('#q1').text(window[myStr + 'arrayquestions'][randomstart]);
    $('#q2').text(window[myStr + 'arrayquestions'][randomstart]);
}

handleQuestion('first');

but why not use an object

var questions = {
    first: {
         questions : ["", "", ""],
         answer1   : ["", "", ""],
         answer2   : ["", "", ""]
    },
    second: {
         ...etc
    }
}

that way you can access them like :

function handleQuestion(myStr) {
    var randomstart = 0; //just for example
    var obj = questions[myStr];

    $('#question').text(obj.questions[randomstart]);
    $('#q1').text(obj.answer1[randomstart]);
    $('#q2').text(obj.answer2[randomstart]);
}

handleQuestion('first');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.