最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

function - Use argument as variable name (Javascript) - Stack Overflow

programmeradmin1浏览0评论

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 that window evaluates to an Object and thus supports properties and normal property access (although some DOM/browser properties are "reserved"). That being said, using window[prop], for an unconstrained prop value, is probably questionable. Consider myObject[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
Add a ment  | 

2 Answers 2

Reset to default 6

Yeah, 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.

发布评论

评论列表(0)

  1. 暂无评论