5

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

4

2 回答 2

10

你需要做:

alert(obj[test].start);
于 2013-03-22T02:02:58.787 回答
-1

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

哎呀!甚至所有东西都是字符串!
从上面的问题,我将对象名、属性名扩展为字符串 Jang!...

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

// 尝试 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()
于 2013-03-22T02:07:33.503 回答