Convert a string to a variable name in javascript?

后端 未结 3 1403
清歌不尽
清歌不尽 2021-01-19 21:43

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 v

相关标签:
3条回答
  • 2021-01-19 22:25

    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];
    
    0 讨论(0)
  • 2021-01-19 22:30

    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.

    0 讨论(0)
  • 2021-01-19 22:34

    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);
    
    0 讨论(0)
提交回复
热议问题