Skip to main content
wfzen
Inspiring
November 11, 2015
Answered

loop to generate variables with different values

  • November 11, 2015
  • 1 reply
  • 871 views

In a quiz, I have user answers saved in an array. At the end of the quiz, I need to extract individual answers to different variables q1, q2, q3, etc. The quiz may be of different total questions so I need it to adjust based on total questions in it. How can I use loop to create variables and capture the values?

So I'd like to change the following:

var q1:int = userAnswersArray[0];

var q2:int = userAnswersArray[1];

var q3:int = userAnswersArray[2];

var q4:int = userAnswersArray[3];

...

to the loop like the one below:

for (i = 0; i < totalQuestion-1; i++)

{

  this["var var q" + i] + ":int" = "userAnswersArray[" + this + "]";

}

It probably has syntax errors that it does not work.

Thanks for your help.

This topic has been closed for replies.
Correct answer Andrei1-bKoviI

If indexes of userAnswersArray are always aligned with question numbers (say, question 1 answer is recorded in position 0, 2 - in position 1, etc.) the following may work:

var urlreq:URLRequest = new URLRequest("subresultpage.asp");

urlreq.method = URLRequestMethod.POST;

var urlvars:URLVariables = new URLVariables();

for(var i:int = 0; i < userAnswersArray.length; i++) {

  urlvars["q" + (i + 1)] = userAnswersArray;

}

1 reply

Ned Murphy
Legend
November 11, 2015

What you attempted has more than syntax errors, it is just not going to work.   Why do you need to do this?  If you already have the data saved there should not be any need to resave it using a different name.

wfzen
wfzenAuthor
Inspiring
November 11, 2015

Thank you, Ned. I need to save individual answers to separate columns of SQL database instead of one array. The only way I know of is to pass each answer as an variable like the lines below. If not possible, I will just manually change based on total questions.

var q1:int = userAnswersArray[0];

var q2:int = userAnswersArray[1];

var q3:int = userAnswersArray[2];

var urlreq:URLRequest = new URLRequest("subresultpage.asp");

urlreq.method = URLRequestMethod.POST;

var urlvars:URLVariables = new URLVariables();

urlvars['q1'] = q1;

urlvars['q2'] = q2;

urlvars['q3'] = q3;

urlvars['q4'] = q4;

...

Thanks,

Andrei1-bKoviICorrect answer
Inspiring
November 18, 2015

If indexes of userAnswersArray are always aligned with question numbers (say, question 1 answer is recorded in position 0, 2 - in position 1, etc.) the following may work:

var urlreq:URLRequest = new URLRequest("subresultpage.asp");

urlreq.method = URLRequestMethod.POST;

var urlvars:URLVariables = new URLVariables();

for(var i:int = 0; i < userAnswersArray.length; i++) {

  urlvars["q" + (i + 1)] = userAnswersArray;

}