Isaac Lubow
Isaac Lubow

Reputation: 3573

Can I refer to a variable using a string?

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?

Upvotes: 6

Views: 302

Answers (7)

SLaks
SLaks

Reputation: 887657

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;

Upvotes: 11

Grzegorz Gierlik
Grzegorz Gierlik

Reputation: 11232

I am not sure what do you want to achieve, but maybe this approach could be better (it depends on some factors like version of HTML you use as @Andy E points in comment below):

<div id="foo" index="123"></div>
<div id="bar" index="456"></div>
<script>
   var fooIndex = document.getElementById("foo").getAttribute("index");
</script>

Here value of index is kept together with corresponding HTML element.

Upvotes: 1

Guffa
Guffa

Reputation: 700472

To answer your question, you can use the eval function to evaluate a string:

thisIndex = eval(this.id + '_index');

However, using the eval function is generally a sign of badly constructed code. I think that you should use an associative array instead:

var numbers = { foo: 123, bar: 456 };
thisIndex = numbers[this.id];

Upvotes: 1

Keith
Keith

Reputation: 155722

I think you want something like this:

// put your properties in an object of some kind
var dictionary = 
{
    foo_index: 123,
    bar_index: 456
};

// you can set further properties with property syntax
dictionary.again_index = 789;

// or dictionary syntax - same result
dictionary['another_index'] = 012;

// then function to get the number value from the index name becomes
var thisIndex = Number(dictionary[this.id + '_index']);

Upvotes: 0

PAP
PAP

Reputation: 11

window["myvar"] = 'hello';

alert(myvar);

Upvotes: 1

reko_t
reko_t

Reputation: 56430

You can. If foo_index and bar_index are global variables, you can simply do:

var thisIndex = window[this.id + '_index'];

Upvotes: 10

tarrasch
tarrasch

Reputation: 2680

you can try using the eval function:

http://www.w3schools.com/jsref/jsref_eval.asp

it does exactly what you need.

Upvotes: 5

Related Questions