javArc
javArc

Reputation: 315

Convert a string to a variable name in javascript?

Ok you have a set of variables:

var height1 = 10
var height2 = 20
...
var height7 = 70;

The user has given input and you need to get the value of one of those variables, here's the code for that:

if(window.location.hash) {
      var hash = window.location.hash.substring(1); 
            var option_name = $('a[name=' + hash + ']').closest('[id^="option"]').attr("id");
            var hash_div_height_id = "height" + option_name.substring(6);
            $('a[name=' + hash + ']').closest('[id^="option"]').show();
            $('a[name=' + hash + ']').closest('[id^="option"]').height(hash_div_height_id);
  } else {
      // No hash found
  }

My problem now being that I can't pass "hash_div_height_id"(which would currently represent the string "height1" or "height2" or whatever number the jQuery returned to append to the end of the string) to the height function as it's a string.

So how can I go about this? Can I somehow convert the string "height1" to represent the variable height1 that was established earlier?

Upvotes: 4

Views: 14602

Answers (3)

Mocksy
Mocksy

Reputation: 370

Do you have control over the variables as an array of heights would suit you much better, failing that, create the array yourself so you take height 1..X push them onto an array and then you can just use the index.

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Assign the height's as properties of an object.

Something like..

var heightObj = {
        height1 : 10,
        height2 : 20,
        height7 : 70
    };

var hash_div_height_id = "height" + option_name.substring(6);

To access the particular property , use the [] notation to access the property

var newHeight = heightObj[hash_div_height_id];
$('a[name=' + hash + ']').closest('[id^="option"]').height(newHeight);

Upvotes: 5

Rune FS
Rune FS

Reputation: 21752

Assuming that the variables are declared in global scope you can just do window[hash]

That because any variable you declare in global scope is attached as a prpoerty to window (assuming the code is run in a browser). and you can get the value of any property either by dot notation

window.height1

or by indexing using the property name as the key. That is

window["height1"]

and since you can pass a variable holding the key you can simply do

var hash = "height1"; //replace with the code you already have
var height = window[hash];

Upvotes: 2

Related Questions