In JavaScript I want to make a function which takes an argument and in this function a variable will be created whose name will be the value of the argument.
For example if user pass "jack" in the argument then in function I want a variable whose name is jack like:
var jack = "";
-
3Why ? What do you want to do next ?Adrien Lacroix– Adrien Lacroix2013年05月15日 14:08:20 +00:00Commented May 15, 2013 at 14:08
-
1Could you explain the use-case?Ja͢ck– Ja͢ck2013年05月15日 14:08:22 +00:00Commented May 15, 2013 at 14:08
-
possible duplicate of "Variable" Variables in Javascript?Felix Kling– Felix Kling2013年05月15日 14:18:03 +00:00Commented May 15, 2013 at 14:18
-
2You want this variable defined in the what scope?techfoobar– techfoobar2013年05月15日 14:18:50 +00:00Commented May 15, 2013 at 14:18
5 Answers 5
Typically, you won't need to do this. As Bergi pointed out, a local variable would usually suffice. However, in the event that you do need to use this technique, you could give the property to the window object:
function setVariable(userPassedString);
window[userPassedString] = "";
}
Don't use eval for this, ever, no matter how tempted you are to.
8 Comments
window isn't that much better.Creating local variables via a function is typically a bad idea. You could accomplish something similar by passing a local object around, e.g.
function setVar(o, name, value)
{
o[name] = value;
}
Then, inside your local scope:
var o = {};
setVar(o, 'jack', 123);
// o.jack contains 123
In this way, if the need would really arise (this is rarely required) to introduce global variables in this manner, you can always call the function like this:
setVar(window, 'jack', 123);
// now window.jack == jack == 123
Comments
The best that you can do about is to create an object and assigns the variable name to the keys of the created object like this -
var myvar={};
function create(var){
myvar[var]='values';
}
Comments
You could always use a dictionary. Here is a very simple stub:
function Dictionary(){
var container = {};
this.set = function(key, value){
container[key] = value;
}
this.get = function(key){
return container[key];
}
}
var vars = new Dictionary();
vars.set('foo', 'foo rocks');
vars.set('bar', 'bar rocks too');
console.log(vars.get('foo'));
console.log(vars.get('bar'));
Comments
To prevent using the window global array, you can create a local array which holds your variables.
function doSomething(var) {
var vars = {};
vars[var] = value;
}