使用参数作为变量名(Javascript)

cbo*_*urn 1 javascript arguments function

我似乎找不到直接回答这个问题的问题。

我想使用函数参数作为该函数内变量的名称。

例如,

test(var1);

function test(foo)
{
    var foo = 'Hello world!'; // Set var1
}

alert(var1); // Hello world!
Run Code Online (Sandbox Code Playgroud)

我可以在这里使用括号(即 window.[ ])吗?

xbo*_*nez 6

是的,你可以使用括号:

window[foo] = "Hello World"
Run Code Online (Sandbox Code Playgroud)

这是一个JSFiddle