在javascript中将字符串转换为变量名称? [英] Convert a string to a variable name in javascript?

查看:85
本文介绍了在javascript中将字符串转换为变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,你有一组变量:

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
  }

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

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.

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

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

推荐答案

将高度指定为属性一个对象。

Assign the height's as properties of an object.

类似......

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

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

要访问特定媒体资源,请使用 [] 表示法访问property

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);

这篇关于在javascript中将字符串转换为变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆