View Full Version : setting a variable with an expression as the name?
neonhomer
03-28-2003, 07:52 PM
I'm trying to set a variable using an expression as the variable's name. I can do this in macromedia flash using:
set ( variableExpression, variableValue)
Is there a way to do this in javascript?
What kind of values can variableExpression be?
If it is just the name of the variable then you can create your own set function.
function set(variableExpression, variableValue)
{
window[variableExpression] = variableValue;
}
for example
set("a", 10);
alert(a);
liorean
03-28-2003, 08:36 PM
Depends on what you mean:
The variable name is unmutable: it will keep it's identifier until destroyed.
So, if you mean that you want to set a variable name to an expression, and the expression can change, no you can't. If you mean you want to evaluate the expression and use that as the variable name, yes you can.
window[variableExpression]=variableName;
// window for global scope, change if that's not the scope you want.
neonhomer
03-28-2003, 09:06 PM
Originally posted by liorean
If you mean you want to evaluate the expression and use that as the variable name, yes you can.
Yes, that's what i want to do and that script works great! Thank you two very much! One thing i don't understand is the window[] part:
window[variableExpression] = variableValue;
I don't quite understand how it works.
In JavaScript you can access member variables using dot notation or as array member variables.
var myObj = new Object()
myObj.a = 10;
alert(myObj.a);
is the same as
alert( myObj["a"] );
All global variables that are declared become are part of the window object so
var a=10;
alert(a);
is the same as
alert(window.a);
is the same as
alert( window["a"] );
Hope that makes sense?
neonhomer
03-28-2003, 09:26 PM
Yes, i wasn't connecting the []'s with the dot notation. :)
Thanks again for all of the help!
cheesebagpipe
03-28-2003, 09:37 PM
http://www.crockford.com/javascript/survey.html :thumbsup:
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.