I can't seem to find a question that answers this directly.
I'd like to use a function argument as the name of a variable within that function.
e.g.,
test(var1);
function test(foo)
{
var foo = 'Hello world!'; // Set var1
}
alert(var1); // Hello world!
Can I use the brackets here (i.e., window.[ ])?
I can't seem to find a question that answers this directly.
I'd like to use a function argument as the name of a variable within that function.
e.g.,
test(var1);
function test(foo)
{
var foo = 'Hello world!'; // Set var1
}
alert(var1); // Hello world!
Can I use the brackets here (i.e., window.[ ])?
Share Improve this question asked Sep 13, 2013 at 2:12 cbourncbourn 1623 silver badges13 bronze badges 2- you mean your variable contains a bracket? or you mean array? – Drixson Oseña Commented Sep 13, 2013 at 2:14
-
Don't think in terms of variables. Think of terms in properties (and how they relate to Maps/Dictionaries/Objects) - properties can have arbitrary string names and can accessed as
obj[propNameExpression]
. Then consider thatwindow
evaluates to an Object and thus supports properties and normal property access (although some DOM/browser properties are "reserved"). That being said, usingwindow[prop]
, for an unconstrained prop value, is probably questionable. ConsidermyObject[prop]
instead. You'll also need to pass in"var1"
as a string value (or the identifier will be evaluated). – user2246674 Commented Sep 13, 2013 at 2:16
2 Answers
Reset to default 6Yeah, you can use brackets:
window[foo] = "Hello World"
Here's a JSFiddle
Er...okay, so this is almost certainly not a good idea.
Short answer: sorta. If you're running in a browser, you can do this:
var polluteGlobalNamespace = function(symbol) {
window[symbol] = "whatever";
};
polluteGlobalNamespace('foo');
console.log(foo);
But that only works for global variables. There is no way to do this with function-scoped variables, because JavaScript lacks first class environments.
But unless you're doing some deep dark metaprogramming, this isn't a good idea. It might be better to post the problem that you're trying to solve with this function to see what the idiomatic way to do it is.