0

I know there are a lot of questions about if it is possible to use variable variables in jQuery.

One of the questions is this one: click here.

I tried to use the answer, but I don't know how I can use it in my case.

var numberofquestions = 10;   
var dataString = "";
for ( var i=1; i<=numberofquestions; i++ ) {
        /* ------ first  part ------- */
        if (i==1) {
            dataString = dataString + "q1=" + question1 + "&";
        } /* ------ end first part ------- */
        else if (i == numberofquestions) {
            questionValue = "question" + numberofquestions;
            qValue = "q" + numberofquestions;
            dataString = dataString + qValue + "=" + questionValue;
            console.log(dataString);
        } else {
            questionValue = question + i;
            dataString = dataString + "q" + i + "=" + questionValue +  "&";

        }
    }

The loop will run 10 times, and each time it needs to add a part to the already existing dataString.

What it needs to do is make this string:

q1=(value of var question1)&q2=(value of var question2) and so forth.

The vars question1, question2, ... question10 all hold a number.

The first part works, it outputs q1=5 in the console log, however, after comes a random string. The output string (the total string) looks like:

q1=5&q2=NaN&q3=NaN&q4=NaN&q5=NaN&q6=NaN&q7=NaN&q8=NaN&q9=NaN&q10=question10

Does anybody know what I'm doing wrong?

Community
  • 1
  • 1
JiFus
  • 959
  • 7
  • 19

1 Answers1

3

You should use an array for this. There is no such thing as "variable variables" in JavaScript.

You can access a variable through a string containing the variables name by using this[variableName], but again, you shouldn't. You should use an array for this.

In your case, you would use questionValue = this["question" + i], but one more time: Don't do it. Use an array instead.

I'm not sure why you're using "question" + numberofquestions which will be 10 every time

user229044
  • 232,980
  • 40
  • 330
  • 338
  • 1
    Wait. i got confused... you're saying "you should use an array for this..." and then "don't use an array"... wait, what..? – T J Jul 10 '14 at 17:13
  • @TilwinJoy There is a tiny period after the bold don't – sharf Jul 10 '14 at 17:17
  • @user3669154 oops... he blends in very well with the dust particles on screen :D – T J Jul 10 '14 at 17:23