我刚读过“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+"'"]
之类奇怪的事情而没有结果。
如何通过将其名称作为字符串传递来创建全局变量?
答案 0 :(得分:4)
在createGlobal内部尝试:
window[strname] = {name:"John", age:27};