按名称访问JavaScript变量的值?

时间:2010-12-09 15:20:29

标签: javascript

您好可以按名称访问JavaScript变量的值吗?例如:

var MyVariable = "Value of variable";


function readValue(name) {
     ....
}


alert(readValue("MyVariable"));

这是可能的,所以输出是“变量值”吗?如果是,我该如何编写这个函数?

由于

7 个答案:

答案 0 :(得分:9)

全局变量在window对象上定义,因此您可以使用:

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

答案 1 :(得分:6)

是的,你可以这样做:

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

答案 2 :(得分:3)

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

这就是全部; o)

答案 3 :(得分:1)

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

答案 4 :(得分:0)

试试这个^ _ ^

var MyVariable = "Value of variable";

alert(readValue("MyVariable"));

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

答案 5 :(得分:0)

我尝试了下面的函数,该函数由Nicolas Gauthier通过Stack Overflow发布,通过命名它来从字符串中获取函数,并且当与变量名一起使用时,它返回变量的值。

它处理点分的变量名(对象的值)。它适用于全局变量和用var声明的变量,但不适用于用'let'定义的变量,在调用函数中不可见。

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

答案 6 :(得分:0)

//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