如何通过将其名称作为字符串传递来创建全局变量?

时间:2013-06-19 22:44:13

标签: javascript global-variables

我刚读过“Define global variable in a JavaScript function”,我想尝试做同样的事情,但这次将字符串作为全局变量名传递。

function createGlobal(strname){
    window.strname={
        name:"John",
        age:27
    };
}

createGlobal("myglobal");

//can't use "alert(myglobal.name);", myglobal is not defined and crashes
//however, this works v
alert(strname.name); //John

我是对象的新手,我也尝试了window.[strname]window.[""+strname+""]window.["'"+strname+"'"]之类奇怪的事情而没有结果。

如何通过将其名称作为字符串传递来创建全局变量?

1 个答案:

答案 0 :(得分:4)

在createGlobal内部尝试:

window[strname] = {name:"John", age:27};