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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With