-2

I'm trying to find a way of using a string to refer to a variable. Here is an example using jQuery:

var array = [1,2,3];

$('.array').click(function(){
    var foo = $(this).attr('class');
    return foo[1];
});

I want this to return the number '2' - but as foo is a string it will return the sub string 'r'.

edit - the answer I was looking for was:

var array = [1,2,3];

$('.array').click(function(){
    var foo = $(this).attr('class');
    return eval(foo)[1];
});
8
  • 3
    I don't get it, what are you trying to do? Commented Jul 3, 2014 at 20:11
  • You seem to be mixing up some major concepts here, please elaborate further on what, how and why you're trying to do. Commented Jul 3, 2014 at 20:13
  • 4
    From what's provided I don't see how it "obviously" returns 2 at all. Commented Jul 3, 2014 at 20:15
  • 1
    Oh yeah... my bad... serious case of skimming Commented Jul 3, 2014 at 20:18
  • 1
    $(this).attr('class'); is probably the string "array" (look at the jQuery selector with .click); OP wants to refer to the variable by name. Commented Jul 3, 2014 at 20:21

1 Answer 1

0

I don't know if this is quite what you mean, but a Javascript object can do this.:

foo = {}; // create object
foo["string"] = [1,2,3]; // now the list [1,2,3] can be referenced
                        //  by foo.string, or foo["string"]
console.log(foo["string"][1]); // Output with string.

Is that what you mean?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.