-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];
});
Hello World
  • 1,102
  • 2
  • 15
  • 33

1 Answers1

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?

Kaia
  • 862
  • 5
  • 21