Access value of JavaScript variable by name?

前端 未结 7 1322
生来不讨喜
生来不讨喜 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]];
    }
    

提交回复
热议问题