Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I refer to a variable using a string?

Tags:

javascript

Say I have the following JS:

var foo_index = 123;
var bar_index = 456;

And the following HTML:

<div id="foo"></div>
<div id="bar"></div>

Then I'd like to say this:

thisIndex = this.id + '_index'

And I'd like thisIndex to be a number. How do I turn the string, which is exactly the variable name, into a variable?

like image 381
Isaac Lubow Avatar asked Aug 25 '10 12:08

Isaac Lubow


1 Answers

You should put the variables in an object, like this:

var indices = { 
    foo: 123,
    bar: 456
};

var thisIndex = indices[this.id];

This code uses JSON syntax an object literal to define an object with two properties and uses [] to access a property by name.

You can also write

var indices = new Object;
indices.foo = 123;
indices["bar"] = 456;
like image 91
SLaks Avatar answered Oct 04 '22 11:10

SLaks