Chapsterj
Chapsterj

Reputation: 6625

Referencing a JavaScript variable

I have 2 variables in a script tag that get populated with string values. I also have an .each loop that goes through each select box I have on the page. I want a way to append the index value of the loop to the name of the variable, and retrieve its value.

var secQuestion1 = "bla"
var secQuestion2 = "bla"

    selectbox.each(function( index ) {
       var question = ['secQuestion' + (index+1) ];
       console.log("question = ", ['secQuestion' + (index+1)] )
    });

I thought I might be able to use bracket notation to retrieve the value. Any ideas on how to do this, so on each index in the loop I would get my questions values?

Upvotes: 0

Views: 65

Answers (2)

hackattack
hackattack

Reputation: 1087

it depends in what context your code is running, if your variables are global then you can do

window['secQuestion' + (index+1)]

you can also put them in an object and access them that way

var obj = {
    secQuestion1: "bla",
    secQuestion2: "bla"
};
selectbox.each(function( index ) {
   console.log("question = ", obj['secQuestion' + (index+1)] )
});

Upvotes: 1

Alex Weinstein
Alex Weinstein

Reputation: 9891

I'd use an array here, for example:

var arrQuestions = ["question A", "question B", "questionC"];

selectbox.each(function( index ) {
   var question = arrQuestions[index];
}

Upvotes: 2

Related Questions