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?
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?
7 Answers
Reset to default 11You 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;
You can. If foo_index and bar_index are global variables, you can simply do:
var thisIndex = window[this.id + '_index'];
you can try using the eval function:
http://www.w3schools.com/jsref/jsref_eval.asp
it does exactly what you need.
window["myvar"] = 'hello';
alert(myvar);
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];
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.
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']);
$
symbol in PHP. – BoltClock Commented Aug 25, 2010 at 12:05