开发者

Access value of JavaScript variable by name?

Hello it is possible to access the value of 开发者_Python百科a JavaScript variable by name? Example:

var MyVariable = "Value of variable";


function readValue(name) {
     ....
}


alert(readValue("MyVariable"));

Is this possible, so that the output is "Value of variable"? If yes, how do I write this function?

Thanks


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

var MyVariable = "Value of variable";
alert(window["MyVariable"]);


Yes, you can do it like this:

var MyVariable = "Value of variable";
alert(window["MyVariable"]);


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)


var sen0=1;
if(window["sen"+n] > 0){
}


Try this ^_^

var MyVariable = "Value of variable";

alert(readValue("MyVariable"));

function readValue(name) {
    return eval(name)
}


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]];
}


//Ran into this today

//Not what I want
var test = 'someString';
var data = [];
data.push({test:'001'});
console.log(test); --> 'someString';
console.log(data); --> 
 (1) [{…}] 
    0: {test: "001"}        //wrong


//Solution
var obj = {};
obj[test] = '001';
data.push(obj);
console.log(data); -->
(2) [{…}, {…}]
    0: {test: "001"}        //wrong
    1: {someString: "001"}  //correct
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜