Access value of JavaScript variable by name?

前端 未结 7 1302
生来不讨喜
生来不讨喜 2020-11-27 07:24

Hello it is possible to access the value of a JavaScript variable by name? Example:

var MyVariable = \"Value of variable\";


function readValue(name) {
             


        
相关标签:
7条回答
  • 2020-11-27 08:11

    I tried the function below which was posted by Nicolas Gauthier via Stack Overflow to get a function from a string by naming it, and when used with the name of a variable, it returns the variable's value.

    It copes with dotted variable names (values of an object). It works with global variables and variables declared with var, but NOT with variables defined with 'let' which are not visible in called functions.

    /***
     * getFunctionFromString - Get function from string
     *
     * works with or without scopes
     *
     * @param  string   string  name of function
     * @return function         by that name if it exists
     * @author by Nicolas Gauthier via Stack Overflow
     ***/
    window.getFunctionFromString = function(string)
    {
        let scope = window; let x=parent;
        let scopeSplit = string.split('.');
        let i;
    
        for (i = 0; i < scopeSplit.length - 1; i++)
        {
            scope = scope[scopeSplit[i]];
    
            if (scope == undefined) return;
        }
    
        return scope[scopeSplit[scopeSplit.length - 1]];
    }
    
    0 讨论(0)
  • 2020-11-27 08:12
    var sen0=1;
    if(window["sen"+n] > 0){
    }
    
    0 讨论(0)
  • 2020-11-27 08:13

    Yes, you can do it like this:

    var MyVariable = "Value of variable";
    alert(window["MyVariable"]);
    
    0 讨论(0)
  • 2020-11-27 08:14

    Global variables are defined on the window object, so you can use:

    var MyVariable = "Value of variable";
    alert(window["MyVariable"]);
    
    0 讨论(0)
  • 2020-11-27 08:14
    var MyVariable = "Value of variable";    
    alert(readValue("MyVariable"));    
    
    // function readEValue(name) { readevalue -> readvalue // always do copy-paste to avoid errors  
    function readValue(name) {   
     return window[name]   
    }   
    

    That's all about ;o)

    0 讨论(0)
  • 2020-11-27 08:21

    Try this ^_^

    var MyVariable = "Value of variable";
    
    alert(readValue("MyVariable"));
    
    function readValue(name) {
        return eval(name)
    }
    
    0 讨论(0)
提交回复
热议问题