我刚读到“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+"'"]
没有结果。
如何通过将其名称作为字符串传递来创建全局变量?
最佳答案
在 createGlobal 中试试这个:
window[strname] = {name:"John", age:27};
关于javascript - 如何通过将其名称作为字符串传递来创建全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17202610/