0

q1 = {
  qTxt: "I want this text to be displayed in the alert box.",
  usedBefore: true
};

var foo = "q1"
alert(eval(foo).qTxt);

While searching other answers on StackOverflow, I found a solution to my problem which uses eval(). But I did read before that eval() is bad (eval is evil) and it shouldn't be used.

If it really is a bad to use it, how could I get the same result.

I heard of something like alert(member['foo']), but when I tried to use it, it didn't work: alert(['foo']qTxt);

EDIT: I didn't get an answer for my problem from the "duplicate". That question only shows how to change the parameter, but I'm trying to change the first part (q1) which seems to be not working for me.

EDIT 2: My code.

q1 = {
  qTxt: "The answer is true.",
  usedBefore: false
};
    
    var foo = "q1";
    alert([foo].qTxt); // without the dot, an error  comes up
Marked as Duplicate
  • 1,117
  • 4
  • 17
  • 39
  • Hmm [this is probably a better duplicate](http://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – Quentin Oct 01 '16 at 18:50
  • Check it over again, I didn't find an answer from what you put as the "duplicate". I actually did look at those questions before I asked this one. – Marked as Duplicate Oct 01 '16 at 18:59
  • You can't access variables with that notation. What you need to do is put `q1` in an object, let's call it `questions`, have a property named `q1` in there, and use `questions[questionName]` to look up the question, assuming `questionName` holds the string "q1". – doug65536 Oct 01 '16 at 19:04
  • 1
    If you simply have `q1`, `q2`, `q3`, etc., in there, why bother? Just use an array. – doug65536 Oct 01 '16 at 19:06
  • @doug65536 - if I'm going to use arrays, how would I target the array names instead, then? – Marked as Duplicate Oct 01 '16 at 19:11
  • If you named the array `questions`, then you would use the `length` property of the array. Each entry is numbered from `0` to `questions.length-1`. You use the same notation, put the array index (the 0-based number) in square brackets: `questions[i]`. Another option, if you want to process all of the questions at once, is to use `questions.forEach(function(question) { /* use question.qTxt etc */ });` – doug65536 Oct 02 '16 at 05:11

0 Answers0