是否可以在javacsript中使函数接受参数,并将其声明为全局变量?例如,我知道这不起作用,但我只是好奇是否有其他方法可行:
function newVar(n){
n = "I'm a global variable";
}
newVar("workPls");
console.log(workPls); //Error: workPls is not defined
答案 0 :(得分:2)
不推荐,但您可以这样做:
function newVar(n){
window[n] = "I'm a global variable";
}
newVar("workPls");
console.log(workPls); // "I'm a global variable"
答案 1 :(得分:0)
也许你可以改用回归?
function newVar(){
return "I'm a global variable";
}
var workPls=newVar();
console.log(workPls);