在javascript中将字符串转换为变量名称?

jav*_*Arc 3 javascript jquery

好的,你有一组变量:

var height1 = 10
var height2 = 20
...
var height7 = 70;
Run Code Online (Sandbox Code Playgroud)

用户已经给出了输入,您需要获取其中一个变量的值,这里的代码是:

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
  }
Run Code Online (Sandbox Code Playgroud)

我现在的问题是我无法将"hash_div_height_id"(当前表示字符串"height1"或"height2"或jQuery返回的任何数字追加到字符串末尾)传递给高度函数,因为它是一个字符串.

那我怎么能这样呢?我可以以某种方式转换字符串"height1"来表示之前建立的变量height1吗?

Sus*_* -- 5

将高度指定为对象的属性.

就像是..

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

var hash_div_height_id = "height" + option_name.substring(6);
Run Code Online (Sandbox Code Playgroud)

要访问特定属性,请使用[]表示法访问该属性

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