变量JS中的变量

Variable Variable in JS

本文关键字:变量 JS      更新时间:2023-09-26

我需要在JS中创建一个变量变量名…

obj = {};
obj.fooonex = {};
obj.fooonex.start = 1;
obj.fooonex.end = 2;
a = "foo";
b = "one";
c = "x";
test = a + b + c;
alert(obj.test.start);

我希望结果是"1"

提琴在这里:http://jsfiddle.net/mR6BH/

你需要做的是:

alert(obj[test].start);

generic 2修复,即更健壮的解决方案

黏糊糊的东西!甚至所有东西都是绳子!!
从上面的问题我扩展objectname,propertyname为字符串Jang!…

objectname = "obj";
propertyname = "start";

//try alert(get(objectname + ".")+ test +"。"

+ propertyname));
function get(path) {
    var next = window;
    path = path.split(/['[']'.]+/);
    if (path[path.length - 1] == "") {
        path.pop();
    };
    while (path.length && (next = next[path.shift()]) && typeof next === "object" && next !== null);
    return path.length ? undefined : next;
}

另一
   function getPropertyValueByPath (obj, path)
    {
        path = path.split(/['[']'.]+/);
        if(path[path.length - 1] == "")
        {
            path.pop();
        };
        while(path.length && ( obj = obj[path.shift()]));
        return obj;
    }
使用

 alert(getPropertyValueByPath(obj,test+ "." + propertyname ));
 alert(get(objectname + "." + test + "." +propertyname));

非推荐方式

eval(objectname + "." + test + "." +propertyname )
Another way `eval("obj." + test + ".start")`
a way of insecure and non-advised eval()