JS中的变量变量

时间:2013-03-22 02:01:57

标签: javascript variables

我需要在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/

2 个答案:

答案 0 :(得分:10)

你需要这样做:

alert(obj[test].start);

答案 1 :(得分:-1)

通用2修复,即更强大的解决方案

goops!甚至每件事都是字符串!!!
从上面的问题我扩展objectname,propertyname为字符串Jang! ...

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

//尝试提醒(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()