Elliot Bonneville
Elliot Bonneville

Reputation: 53311

How to use contents of array as variables without using eval()?

I have a list of variables or variable names stored in an array. I want to use them in a loop, but I don't want to have to use eval(). How do I do this? If I store the values in an array with quotes, I have to use eval() on the right side of any equation to render the value. If I store just the variable name, I thought I'd be storing the actual variable, but it's not working right.

$(data.xml).find('Question').each(function(){
  var answer_1 = $(this).find("Answers_1").text();
  var answer_2 = $(this).find("Answers_2").text();
  var answer_3 = $(this).find("Answers_3").text();
  var answer_4 = $(this).find("Answers_4").text();
  var theID = $(this).find("ID").text();
  var theBody = $(this).find("Body").text();

  var answerArray = new Array();

  answerArray = [answer_1,answer_2,answer_3,answer_4,theID,theBody]

  for(x=0;x<=5;x++) {
    testme = answerArray[x];

    alert("looking for = " + answerArray[x] + ", which is " + testme)
  }
});

Upvotes: 4

Views: 379

Answers (3)

John Hartsock
John Hartsock

Reputation: 86882

This would make it easier to get the array populated.

var answers = new Array();
$("Answers_1, Answers_2, Answers_3, Answers_4", this).text(function(index, currentText) {
  answers[index] = currentText;
});

Upvotes: 1

SLaks
SLaks

Reputation: 887479

You can put the values themselves in an array:

var answers = [
    $(this).find("Answers_1").text(),
    $(this).find("Answers_2").text(),
    $(this).find("Answers_3").text(),
    $(this).find("Answers_4").text()
];

for(x=0;x<=5;x++) {
    alert("looking for = " + x + ", which is " + answers[x])
}

EDIT: Or even

var answers = $(this)
    .find("Answers_1, Answers_2, Answers_3, Answers_4")
    .map(function() { return $(this).text(); })
    .get();

If your answers share a common class, you can change the selector to $(this).find('.AnswerClass').

If you need variable names, you can use an associate array:

var thing = { 
    a: "Hello",
    b: "World"
};

var name = 'a';
alert(thing[name]);

Upvotes: 3

pkaeding
pkaeding

Reputation: 37643

As others have mentioned, if you can put the variables in an array or an object, you will be able to access them more cleanly.

You can, however, access the variables through the window object:

var one = 1;
var two = 2;
var three = 3;

var varName = "one";

alert(window[varName]); // -> equivalent to: alert(one);

Of course, you can assign the varName variable any way like, including while looping through an array.

Upvotes: 0

Related Questions